JSONP request returning error: “Uncaught SyntaxError: Unexpected token :”

醉酒当歌 提交于 2019-11-27 19:44:07

You have to set an unconventional parameter to get the SO API to work. Rather than the conventional callback, you need to pass a jsonp parameter.

Furthermore, you can't do POST with 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'                                                                                                                                                
});

It is not possible to do cross-domain AJAX using the conventional XMLHTTPRequest. This is for security reasons (it's call the same-origin policy).

There is a workaround. script tags are not subject to this restriction. This means that you can insert a script tag into the document that calls a URL. If you define a globally-accessible function in your script and tell the remote server what that function is called, the server can pass code that wraps the data to be sent in a call to that function.

The difficulty you had here is with the StackOverflow API. Conventionally, you would use the callback argument in your request, to tell the server what your function is called. However, StackOverflow's API asks you to use the jsonp parameter instead.

Mörre

Try this URL: http://api.stackoverflow.com/1.1/stats?jsonp=callme

"callme" is the name of your callback function - in your GLOBAL NAMESPACE (window object).

By the way, if you are running Firefox and have the JSONView add-on installed you can test the above URL (and yours for comparison) directly.

Result from calling the URL:

callme({
  "statistics": [
...
  ]
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!