[英]add header in ajax for Cross-Origin, not working
当我在Ajax中添加标头HTTP_X_REQUESTED_WITH
以请求到另一台服务器时,它会为erorr提供Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.xxxxxxxxxxxx.com/checkurl.php?action=xxxxxxx. This can be fixed by moving the resource to the same domain or enabling CORS.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.xxxxxxxxxxxx.com/checkurl.php?action=xxxxxxx. This can be fixed by moving the resource to the same domain or enabling CORS.
如果我删除此标头,则它可以正常工作。
我有很多ajax请求,所以我使用这种格式在所有ajax请求中添加标头
$(document).ajaxSend(function (event, jqxhr, settings) {
jqxhr.setRequestHeader('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest')
});
我的ajax是:
$.ajax({
url:sitePath+'Xxxxxxxxx/checkurl.php?action=Pages&page='+actionPage,
type :'POST',
crossDomain:true,
success : function(data){
hideLoadingDiv();
if(data.getElementsByTagName("message")[0].getElementsByTagName("messageType")[0].childNodes[0].nodeValue=="SUCCESS")
{
document.getElementById(divID).innerHTML=data.getElementsByTagName("PageBody")[0].childNodes[0].nodeValue+'<span><a onclick="return checkRegistrationValidation();" href="javascript:void(0);" class="orengeBtn">Back</a></span>';
displayDiv(divID);
}
else if(data.getElementsByTagName("message")[0].getElementsByTagName("messageType")[0].childNodes[0].nodeValue=="ERROR")
{
showErrorMessage(data.getElementsByTagName("message")[0].getElementsByTagName("messageText")[0].childNodes[0].nodeValue);
}
else
{
generalError();
}
},
error:function(xhr,ajaxOptions, thrownError){
hideLoadingDiv();
if(xhr.status==200){
generalError();
}
else{
networkError();
}
if(debugMode==1){
displayAjaxError(xhr,thrownError);
}
}
});
在我的服务器文件中
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: X-Requested-With, Content-Type')
但是每次添加标题时都会出错。 并取出后正常工作。 请帮忙。
您可以在这里找到答案:
您必须在ajax中手动添加标头:
$.ajax({ url:sitePath+'Xxxxxxxxx/checkurl.php?action=Pages&page='+actionPage, type :'POST', crossDomain:true, headers: {'X-Requested-With': 'XMLHttpRequest'}
或使请求不跨域:
$.ajax({ url:sitePath+'Xxxxxxxxx/checkurl.php?action=Pages&page='+actionPage, type :'POST', crossDomain:false,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.