Ajax呈指数级增长,大量请求使服务器陷入困境——JQUERY



我知道问题是什么,但我不知道解决办法。

假设有4个文件。index.php文件、ajax.php文件、more-ajax.php文件和custom.js文件。

在我的索引文件中,我有一个<div id="content"></div>元素,它将从ajax.php文件加载内容。现在我们说,在这个ajax。php文件中,我有以下<div id="moreContent"></div>在我的custom。js文件中,我有以下jquery代码包含在index。php和ajax。php文件中

$(document).ready(function(){
     $("#select-menu").change(function(){
          $("#content").load('ajax.php');
     });
     $("#select-menu-two").change(function(){
          $("#moreContent").load('more-ajax.php');
     });
});

现在,这是有效的,但是我可以看到,每次调用我都一遍又一遍地调用custom.js文件,导致请求呈指数级增长。对此的解决方案是我从ajax.php中删除custom.js。但是…然后第二个ajax函数#select-menu-two不再工作,我不能从more-ajax.php加载内容。

有更好的方法吗?我可以看一下代码示例吗?

谢谢,SC

避免为元素添加多个类似的事件处理程序,请先删除先前添加的事件处理程序:

$(document).ready(function(){
     $("#select-menu").off('change');
     $("#select-menu").change(function(){
          $("#content").load('ajax.php');
     });
     $("#select-menu-two").off('change');
     $("#select-menu-two").change(function(){
          $("#moreContent").load('more-ajax.php');
     });
});

最新更新