[英]Cross-domain POST request ajax in internet explorer
我正在使用jQuery 1.7.2,並希望向另一個域發出POST請求。 它必須是POST請求。 但這在Internet Explorer中不起作用 (我試過IE9); 它適用於所有其他瀏覽器。
我有這個腳本:
<script>
jQuery.support.cors = true;
jQuery(function() {
$.ajax({
crossDomain : true,
cache: false,
type: 'POST',
url: 'http://someotherdomain/test.php',
data: {},
success: function(da) {
console.log(JSON.stringify(da))
},
error: function(jqxhr) {
console.log('fail')
console.log(JSON.stringify(jqxhr))
},
dataType: 'json'
});
});
</script>
我收回錯誤:
{"readyState":0,"status":0,"statusText":"Error: Access denied.\r\n"}
我的PHP文件如下所示:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS');
echo json_decode(array('success' => 'yes'));
Internet Explorer(包括IE9)不支持CORS 。 您必須代理所有跨域請求(在同一個域上發布到PHP腳本,重新發布卷曲查詢並返回響應)
要在IE <10中支持CORS,必須修改ajax方法以使用XDomainRequest對象。 這個插件為你做到了: https : //github.com/jaubourg/ajaxHooks
您的腳本看起來正確但我相信您需要更改:
header('Access-Control-Allow-Origin: *');
至
header('Access-Control-Allow-Origin: x-requested-with');
要么
header('Access-Control-Allow-Origin: {Origin}');
其中{Origin}是Origin標頭的值。 我的理解是,如果給出了Origin,那么放'*'將不起作用。
此外,IE8和IE9對此的支持有限,但如果你把jQuery.support.cors = true
,它確實有效。
這適用於IE9。
<!DOCTYPE html>
<head>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
var url = "http://msdn.microsoft.com/en-us/library/windows/desktop/ms759148(v=vs.85).aspx";
function getRequest() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {alert("Error while getting 6.0");}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {alert("Error while getting 3.0");}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {alert("Error while getting 2.0");}
throw new Error("This browser does not support XMLHttpRequest.");
};
var request = getRequest();
request.open("POST", url, false);
request.send();
alert("Content from :"+url+":"+ request.responseText);
</script>
</head>
<h1>AJAX ActiveX</h1>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.