这是两个页面,test.php和testserver.php.
test.php的
<script src="scripts/jq.js" type="text/javascript"></script>
<script>
$(function() {
$.ajax({url:"testserver.php",
success:function() {
alert("Success");
},
error:function() {
alert("Error");
},
dataType:"json",
type:"get"
}
)})
</script>
Run Code Online (Sandbox Code Playgroud)
testserver.php
<?php
$arr = array("element1",
"element2",
array("element31","element32"));
$arr['name'] = "response";
echo json_encode($arr);
?>
Run Code Online (Sandbox Code Playgroud)
现在我的问题是:当这两个文件都在同一台服务器(localhost或web服务器)上时,它可以工作并被alert("Success")
调用; 如果它位于不同的服务器上,意味着Web服务器上的testserver.php和localhost上的test.php,它就无法工作,并且alert("Error")
正在执行.即使ajax中的URL更改为http://domain.com/path/to/file/testserver.php
如何正确使用XDomainRequest重写Ajax请求以使其在IE 8 +中工作?
$.ajax({
type: "GET",
url: url,
success: function(xml) {
$('.post-msg').append(processXml(xml, config));
},
error: function(jqXhr, textStatus, errorThrown) {
var errorMsg = "Request on url: " + url + " failed: " + textStatus + " error:" + errorThrown;
alert(errorMsg);
}
});
Run Code Online (Sandbox Code Playgroud)