簡體   English   中英

jQuery ajax 完成循環

[英]jQuery ajaxComplete cycling

我有一個代碼:

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

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

但是 $.get cyclnig ajaxComplete 事件 :(

以某種方式存在,如何將 HTML 內容從我的 URL 獲取到變量以使用此變量(查找類和內容)或以某種方式,如何僅對 $.get 的過程禁用 ajaxComplete 事件?

您可以在ajaxComplete檢查請求的 URL。 如果它是您在DoSomething請求的 URL,請不要再次調用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM