Why does a single Ajax call work fine, but consecutive Ajax calls fail?

百般思念 提交于 2019-12-04 03:53:13

The problem is in how jQuery works with callback with JSONP. Here's the idea:

  1. JSONP is fired;
  2. Callback is set;
  3. JSONP returns;
  4. Callback is fired;
  5. Callback is deleted;

Now everything works fine if you don't define custom jsonpCallback (by default jQuery assigns unique callback to each JSONP request). Now what happens if you do and you fire two JSONP request at the same time?

  1. JSONP1 is fired;
  2. Callback with name callback is set.
  3. JSONP2 is fired;
  4. Callback callback is overriden by JSONP2;
  5. JSONP1 returns;
  6. Callback callback is fired for JSONP1;
  7. JSONP1 deletes callback;
  8. JSONP2 returns;
  9. JSONP2 tries to fire callback, but that is already deleted;
  10. TypeError is thrown.

Simple solution is not to override jsonpCallback option.

tusar

As Alex Ball have suggested you need to put your AJAX requests in queue, so that they are executed one by one. It is very simple as shown here in a post in stackoverflow (yes it works for JSON-P also).

The second thing is error message Property 'callback' of object [object Window] is not a function is just because you dont have a global function named callback. Just define it like :

window.callback= function(responseText) {
    //alert(responseText);
};

Hope this helps.

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