简体   繁体   English

ajax调用中的getJSON导致无限循环

[英]getJSON within ajax call causing infinite loop

I am currently calling external php files and displaying them within specific div. 我目前正在调用外部php文件,并在特定的div中显示它们。 This is all done using the standard jQuery $.ajax call. 全部使用标准jQuery $ .ajax调用完成。

However an issue arises when one of the pages being pulled in attempts the following getJSON call, resulting in an infinite loop: 但是,当其中一个页面被拉入尝试以下getJSON调用时,会导致无限循环:

function getContacts() {
  if ($('body.all-contacts').length){
    $.getJSON('assets/data/contacts.json', function(data) {
      var template = $('#contacts-template').html();
      var info = Mustache.to_html(template, data);
      $('.contact-list').html(info);
    });
  }
};

The above function is called as follows: 上面的函数调用如下:

$(document).ajaxComplete(function(){
....
getContacts();
....
})

I've also tried using ajaxStop() instead of ajaxComplete() but the issue persists. 我也尝试使用ajaxStop()而不是ajaxComplete(),但问题仍然存在。

The infinite loop seems normal to me. 无限循环对我来说似乎很正常。 Since you call the function getContacts when the getJSON is completed, getContacts contains the getJSON call so the call will fire again, which will result in another ajaxcomplete callback, which will fire the getContacts function again. 由于您在getJSON完成时调用了getContacts函数,因此getContacts包含getJSON调用,因此该调用将再次触发,这将导致另一个ajaxcomplete回调,该回调将再次触发getContacts函数。 etc etc. 等等等

To prevent this from happening you can remove the getContacts() in the ajaxcomplete function. 为了防止这种情况的发生,您可以删除ajaxcomplete函数中的getContacts()。

If you wish to keep the infinite loop but with time intervals between every ajax call you can use the javascript function setTimeout. 如果您希望保持无限循环,但每个ajax调用之间都有时间间隔 ,则可以使用javascript函数setTimeout。 format of function: 功能格式:
setTimeout("javascript function",milliseconds);

getContacts() should not be called, when a getContacts() call completes. getContacts()不应该叫,一个当getContacts()调用完成。

If you need to call that function, when another one completes, make sure (using if ... ) that it is not getContacts() that completed. 如果您需要调用该函数,则在另一个函数完成时,请确保( if ...使用if ... )不是getContacts()完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM