(这是我另一个类似答案的复制粘贴)。您可以尝试启用“jQuery.support.cors=true”标志,看看效果如何。我使用 jQuery v1.7.2。
我必须从本地磁盘“file:///C:/test/htmlpage.html”加载网页,调用“http://localhost/getxml.php”url,并在 IE8+ 和 Firefox12+ 浏览器中执行此操作,使用 jQuery v1.7.2 lib 来最小化样板代码。看了几十篇文章终于弄明白了。这是我的总结。
- 服务器脚本(.php、.jsp、...)必须返回 http 响应标头 Access-Control-Allow-Origin: *
- 在使用 jQuery ajax 之前,请在 javascript 中设置此标志:jQuery.support.cors = true;
- 你可以在使用 jQuery ajax 函数之前设置一次或每次标志
- 现在我可以在 IE 和 Firefox 中读取 .xml 文档了。我没有测试的其他浏览器。
- 响应文档可以是纯文本、xml、json 或任何其他格式
这是一个带有一些调试系统输出的示例 jQuery ajax 调用。
jQuery.support.cors = true;
$.ajax({
url: "http://localhost/getxml.php",
data: { "id":"doc1", "rows":"100" },
type: "GET",
timeout: 30000,
dataType: "text", // "xml", "json"
success: function(data) {
// show text reply as-is (debug)
alert(data);
// show xml field values (debug)
//alert( $(data).find("title").text() );
// loop JSON array (debug)
//var str="";
//$.each(data.items, function(i,item) {
// str += item.title + "\n";
//});
//alert(str);
},
error: function(jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});