我正在使用 JSONP进行api跨域请求,外部服务器以XML格式返回结果,下面是我的代码: $.ajax({ type: "Get", url: "http://domain.com/function?Data=1234567890", xhrFields: {withCredentials: true}, dataType: "JSONP text x
$.ajax({
type: "Get",
url: "http://domain.com/function?Data=1234567890",
xhrFields: {withCredentials: true},
dataType: "JSONP text xml",
contentType: "application/xml",
cache: false,
success: function(xml)
{
alert($(this).find('ResponseStatus').text());
}
});
它返回一个xml,但随之而来的是它会产生一个错误,说“Unexpected token<”不幸的是,我停止处理,我没有收到警报消息.任何的想法? 最好
正如上面的评论中提到的,来自javascript的跨域xml是禁止的,除非您可以控制正在吐出XML的应用程序,并且可以使用格式化技巧来“欺骗”脚本将其解析为JSON.如果你能做到这一点,那么问题就是为什么不首先只是格式化为JSON?
所以…选项
>格式化应用程序的输出以便使用JSONP进行处理.假设你不能在你的情况下那样做那么……
>在您的网络服务器上使用本地代理. PHP,python或任何其他没有跨域限制的语言都有很多简单的代理示例.至于页面上的脚本然后关注它是一个本地AJAX请求.如果你做不到那么……
>一种可能性是使用像yql这样的中介. yql和jquery可以使很多这些xml问题消失.当然,缺点是您通过您无法控制的第三方发送内容.
像这样的东西:
// find some demo xml - DuckDuckGo is great for this
var xmlSource = "http://api.duckduckgo.com/?q=StackOverflow&format=xml"
// build the yql query. Could be just a string - I think join makes easier reading
var yqlURL = [
"http://query.yahooapis.com/v1/public/yql",
"?q=" + encodeURIComponent("select * from xml where url='" + xmlSource + "'"),
"&format=xml&callback=?"
].join("");
// Now do the AJAX heavy lifting
$.getJSON(yqlURL, function(data){
xmlContent = $(data.results[0]);
var Abstract = $(xmlContent).find("Abstract").text();
console.log(Abstract);
});
当然,在该示例中,您将恢复所有xml数据并在本地搜索 – 选项是调整select语句以恢复您想要的内容.
希望有所帮助
