javascript - jQuery ajax 完全循环
问题描述
我有一个代码:
$(document).ajaxComplete(function() {
DoSomething();
});
function DoSomething() {
...
$.get(MyUrl, function() {
...
});
...
}
但是 $.get cyclnig ajaxComplete 事件:(
以某种方式存在,如何将我的 URL 中的 HTML 内容获取到变量中以使用该变量(查找类和内容)或以某种方式,如何仅对带有 $.get 的进程禁用 ajaxComplete 事件?
解决方案
您可以在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>
推荐阅读
- spring-boot - SpringBoot 检索现有的原型 bean
- html - 填充网格&
带有 JSON 数据文件
- javascript - 在参考服务器时间的特定日期和时间重定向页面
- java - 不能用不同类型的参数继承
- systemd - 如何让systemd等到进程启动
- php - 如何获取位置id中的最后一个元素
- php - 如何使用 ECB 密码模式和 PKCS7 块填充模式使用 Twofish 加密?
- drupal - 如果我在 Drupal 8 中有两种内容类型,它们之间存在关系,为什么我要在两种内容类型中都放置一个引用字段?
- ios - CollectionViewCell 效果
- mysql - mysql安全安装的厨师食谱