jQuery + JSONP + Yahoo Query Language

青春壹個敷衍的年華 提交于 2019-12-03 08:35:07

If available, use the jsonpCallback parameter in the call to $.ajax like:

 jsonpCallback: "cbfunc",

Its description, from the jQuery API docs reads:

Specify the callback function name for a jsonp request. This value will be used instead of the random name automatically generated by jQuery.

The docs later go on to say:

It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests.

However it is not advised to make use of this "preferable" behaviour when making use of YQL. Precisely why that approach is not ideal might make this answer far too verbose, so here is a link (from the YQL blog) detailing the problems with jQuery's preferred approach, making use of jsonpCallback and so on: Avoiding rate limits and getting banned in YQL and Pipes: Caching is your friend

You should let jQuery handle the callback by changing urlToWebservice to end in callback=?

The reason it's not working is because by specifying callback=cbfunc in the querystring generates a URL of the type:

http://query.yahooapis.com/...&callback=cbfunc&callback=jsonp1277417828303

Stripped out all uninteresting parts, but the URL contains two callback parameters. One of them is managed by jQuery, and the other one not. YQL only looks at the first callback parameter and returns a response wrapped around that.

cbfunc({"query":{...}});

However, there is no function named cbfunc in your script, so that's why you are getting the undefined error. jQuery created an implicit function named jsonp1277417828303 in the above example, and the response from YQL should instead have been:

jsonp1277417828303({"query":{...}});

for jQuery to act upon it, and return the response to your success callback which it never got to do.

So, as @SLaks suggested, remove the &callback=cbfuncfrom your URL, or replace it with &callback=? to let jQuery handle things.

See a working example.

You definitely should give jQuery-JSONP a try: http://code.google.com/p/jquery-jsonp/

Simplifies everything :)

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