the*_*ham 25 javascript ajax jquery stackexchange-api
所以我试图使用以下jQuery代码向Stack Exchange API发出请求:
$.ajax({
type: 'POST',
url: 'http://api.stackoverflow.com/1.1/stats',
dataType: 'jsonp',
success: function() { console.log('Success!'); },
error: function() { console.log('Uh Oh!'); }
});
Run Code Online (Sandbox Code Playgroud)
但是当我在我的机器上打开文件,在FireFox或Chrome中,并发出请求时,我收到此错误:
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token :
Uh Oh!
Run Code Online (Sandbox Code Playgroud)
我不知道发生了什么事.我知道Stack Exchange API Gzips它的响应,这会导致任何麻烦吗?
lon*_*day 21
您必须设置非常规参数才能使SO API正常工作.而不是传统的callback,你需要传递一个jsonp参数.
此外,您无法POST使用JSONP.
$.ajax({
type: 'GET',
url: 'http://api.stackoverflow.com/1.1/stats',
dataType: 'jsonp',
success: function() { console.log('Success!'); },
error: function() { console.log('Uh Oh!'); },
jsonp: 'jsonp'
});
Run Code Online (Sandbox Code Playgroud)
使用传统的XMLHTTPRequest无法进行跨域AJAX.这是出于安全原因(它称为同源策略).
有一个解决方法. script标签不受此限制.这意味着您可以script在调用URL的文档中插入标记.如果在脚本中定义全局可访问的函数并告诉远程服务器调用该函数,则服务器可以传递包含要在调用该函数时发送的数据的代码.
您遇到的困难在于StackOverflow API.通常,您可以callback在请求中使用参数,告诉服务器您的函数调用了什么.但是,StackOverflow的API会要求您使用该jsonp参数.
| 归档时间: |
|
| 查看次数: |
54238 次 |
| 最近记录: |