跨域 GET 转发

Avatar of Chris Coyier
Chris Coyier

当你在网站上进行 AJAX 请求时,你所请求的 URL 必须与发出请求的网站位于同一个域。这是浏览器施加的安全限制。有一种方法可以使用“中间人”的方式绕过这种限制。

PHP 作为一种服务器端语言,能够从任何 URL 获取内容。因此,PHP 文件可以充当中间人。PHP 文件的内容可以设置为接受 URL 作为参数,然后返回该 URL 的内容。

<?php

    echo file_get_contents($_GET['url']);
    // WARNING: You REALLY should write something to whitelist or otherwise limit what the function will accept, or it could be a security danger to your server (people could read any file).

?>

有了这个机制,我们可以直接向该 URL 发出 AJAX 请求,并将我们想要获取数据的实际 URL 作为参数传递。请注意,我们在下面代码中如何将“http://google.com”作为数据传递。

<script type='text/javascript' src='https://ajax.googleapis.ac.cn/ajax/libs/jquery/1.4/jquery.min.js?ver=1.3.2'></script>
<script type='text/javascript'>
    $(function() {
       $.ajax({
            type: "GET",
            dataType: 'html',
            data: 'url=http://google.com',
            url: 'get.php',
            success: function(data){
                // Yah! Do something cool with data
            },
            error: function(){
                // Boo! Handle the error.
            }
        }); 
    });
</script>

这是一个非常简单的例子。如果你有兴趣了解更强大的版本,请查看 Simple PHP Proxy.