[英]Ajax call on different server
我正在使用下面提到的腳本在不同的服務器上發送ajax call
。
$(document).ready(function() {
var uniqcod=$(".piczhu-widget").attr('id');
$.ajax({
url:'File Path...',
type:'post',
data:{uniId:uniqcod},
success: function(result){
$('.abcClass').html(result);
}
});
});
腳本沒有收到任何回復 。 此腳本在同一台服務器上正常運行。 是否有任何其他參數可用於在不同服務器上發送呼叫?
這應該使用JSONP解決問題:
$.ajax({
url:'File Path...',
type:'post',
data:{uniId:uniqcod},
dataType: 'jsonp', // use JSONP
success: function(result){
$('.abcClass').html(result);
}
});
});
這是因為跨域策略。 這是安全的事情。 我建議您將該請求發送到位於您的服務器(您的域)上的cURL的PHP文件。
但是你需要在你的服務器上安裝cURL: http : //curl.haxx.se/如果你使用的是基於Debian的服務器,你可以通過以下方式完成:sudo apt-get install php5-curl
例:
<?php
$data = $_POST['data'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "URL FOR REQUEST");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
?>
你需要使用jsonp或cors來跨域ajax。 下面給出的代碼是cors的一個例子
示例代碼:
jQuery.support.cors = true;
function CrosDom_ajax(url) {
if (window.XDomainRequest
&& $.browser.msie
&& $.browser.version < 10) {
xdr = new XDomainRequest();
if (xdr) {
xdr.onload = function () {
alert(xdr.responseText);
};
xdr.open("get", url);
xdr.send();
}
}
else {
$.ajax({
url: url,
success: function (response) {
},
error: function (data) {
}
});
}
}
您還需要在服務器端編寫以下代碼,以允許跨域訪問
Response.AppendHeader("Access-Control-Allow-Origin", "*");
最好的和接受的方法是使用JSONP與不同的服務器通信。 JSONP是一個很好的解決跨域腳本錯誤的方法。
閱讀以下鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.