Why do a random number of these JSONP requests fail?

我的梦境 提交于 2019-12-08 10:49:05

问题


I have a jQuery each loop that runs through a list of three JSONP urls, but, a random number of them just fail with the error: Uncaught TypeError: Property 'callback' of object [object Window] is not a function.

It is usually one or two and sometimes none but it is never all of them, I think that it has to do with the asynchronous part but I don't know how to fix it.

Here is my code:

var feeds = ["JSONPUrl", "JSONPUrl", "JSONPUrl"];

$.each(feeds, function(index, feedUrl) {
    $.ajax({
    type: "GET",
    url: feedUrl,
    processData : true,
    data: {
        tagmode: "any",
        jsonp: "callback",
        callback: "callback"
    },
    jsonpCallback: "callback",
    dataType: "jsonp",
    success: function(data) {
        // Do some DOM manipulations with the data
    },
    error: function(x,y,z) {
    }
});
});​

Any ideas?


回答1:


Your URL looks like ?callback=callback, because of the hard-coded callback property. Remove this, jQuery will automatically define temporary functions with random names for the JSONP callback.

data: {
    tagmode: "any",
    jsonp: "callback",     // <-- Do not forget to remove the trailing comma
    callback: "callback"   // <-- Remove this!
},
jsonpCallback: "callback", // <-- Remove this!

If you really want to execute a function called callback on success, include this in the success handler.

Regarding the comments: If your server expects the JSONP callback parameter to be called "jsonp" instead of "callback", use:

$.ajax({
    ...
    jsonp: "jsonp"
    ...
});
// results in http://..../?jsonp=jQuery234254342random2342etc


来源:https://stackoverflow.com/questions/11477982/why-do-a-random-number-of-these-jsonp-requests-fail

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