【发布时间】:2012-05-22 14:19:31
【问题描述】:
我尝试使用 AJAX(post 请求)调用 eBay FindProducts API,但遇到以下错误:
XMLHttpRequest 无法加载 http://open.api.ebay.com/shopping?callname=FindProducts。 Access-Control-Allow-Origin 不允许来源http://localhost.com/test.php。
我的代码:
$.ajax
({
type: "POST",
url: 'http://open.api.ebay.com/shopping?callname=FindProducts',
dataType: ($.browser.msie) ? "text" : "xml",
contentType: 'application/x-javascript',
crossDomain : true,
data: {
'X-EBAY-API-APP-ID' : 'ebayAppId',
'X-EBAY-API-VERSION': '771',
'X-EBAY-API-SITEID': '0',
'X-EBAY-API-REQUEST-ENCODING': 'NV',
'X-EBAY-API-RESPONSE-ENCODING': 'json',
'QueryKeywords' : '753759971632',
'MaxEntries' : '3'
},
success: function (result) {
alert('success');
alert(result);
},
error: function (data) {
alert((data));
}
})
我怎样才能解决这个错误。
我尝试设置dataType : jsonp(我知道正在检索 XML,但为了解决该错误,我将其设置为 jsonP)。它可以工作,但 jQuery 无法像预期的 json 响应那样解析 XML。
【问题讨论】:
-
"我尝试设置 dataType : jsonP" - 它不起作用,因为 JSONP 不是 XML,反之亦然。尝试检查 ebay 是否支持CORS,以便您可以读取 XML。
-
您可能必须在服务器端执行此操作。您将对您的服务器进行 ajax 调用,从页面传递您需要的任何信息。然后,使用 curl 之类的方法在 php 中访问 api。
-
您好约瑟夫,感谢您的回复。我知道 json 不是 xml,反之亦然(在我尝试设置 dataType : jsonP 后,请参阅我在 () 中的帖子)。如果 eBay 不支持 CORS,有没有办法做到这一点?即使在将 dataType 设置为 jsonp 或脚本之后,有没有办法检索 xml(我从浏览器控制台看到正在检索 xml,但 jquery 无法解析它。)? lbstr -thansk 您的回复,我知道使用 curl/php 实现这一点的方法 :) 。我想看看这是否可以在客户端完成。
-
albin 的方案可以解决这个问题,但是,你想让你的 appid 公开吗?
-
appid公开就好了,不知道为什么jquery无法解析响应,ajax返回错误!