我正在练习AJAX和RESTful Web服务,我在控制台上收到一个错误,上面写着:
阻止跨来源请求:同源策略不允许读取位于的远程资源。。。等等等等。。。
所以,除了Safari,我的代码不会在任何浏览器上运行!在Chrome、Firefor或Opera等其他浏览器上,我都遇到了同样的错误。
只要我在互联网上搜索过,我发现实现这一点的唯一方法是制作一个代理服务器,它会将请求发送到服务器,然后在响应上添加一些头返回到客户端。
www.corsproxy.com解决方案很棒,但我只想拥有自己的代理!:-)
我的简单jQuery代码是:
var dataURL = "http://fou.com/last.json";
$.ajax({
url: dataURL,
async: true,
type: "GET",
dataType: "json",
success: editData
// editData it's a function which gonna edit the data from fou.com ..
})
php代码将是根据这一点编写的?
您可以这样做:
JS:
var dataURL = "http://fou.com/last.json";
var proxyUrl = "http://myproxy.com/?get=";
$.ajax({
url: proxyUrl+encodeURIComponent(dataURL),
async: true,
type: "GET",
dataType: "json",
success: editData
})
PHP部分位于http://myproxy.com:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $_GET['get']
));
curl_exec($curl);
?>
PHP部分经过了非常简化,为您提供了一个想法。