首页 > 解决方案 > jQuery ajax 完全循环

问题描述

我有一个代码:

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

function DoSomething() {
 ...
 $.get(MyUrl, function() {
   ...
 });
 ...
}

但是 $.get cyclnig ajaxComplete 事件:(

以某种方式存在,如何将我的 URL 中的 HTML 内容获取到变量中以使用该变量(查找类和内容)或以某种方式,如何仅对带有 $.get 的进程禁用 ajaxComplete 事件?

标签: javascriptjqueryajax

解决方案


您可以在ajaxComplete. 如果是您在 中请求的 URL,请DoSomething不要再调用DoSomething

$(document).ajaxComplete(function(_, __, { url }) {
  if (url === 'https://jsonplaceholder.typicode.com/posts/1') {
    console.log("Recursion detected, don't do anything");
  } else {
    console.log('Calling DoSomething');
    DoSomething();
  }
});

function DoSomething() {
 $.get('https://jsonplaceholder.typicode.com/posts/1', function() {
   console.log('DoSomething done');
 });
}

$.get('https://jsonplaceholder.typicode.com/posts/5');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

您还可以在传递给的选项对象上设置一个属性$.get,并检查该属性是否存在于.ajaxComplete

$(document).ajaxComplete(function(_, __, { fromDoSomething }) {
  if (fromDoSomething) {
    console.log("Recursion detected, don't do anything");
  } else {
    console.log('Calling DoSomething');
    DoSomething();
  }
});

function DoSomething() {
 $.get({
   url: 'https://jsonplaceholder.typicode.com/posts/1',
   fromDoSomething: true
 }, function() {
   console.log('DoSomething done');
 });
}

$.get('https://jsonplaceholder.typicode.com/posts/5');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


推荐阅读