AJAX call fired multiple times

北慕城南 提交于 2021-02-08 11:13:06

问题


I have a php application to upload excel files to server.I use ajax to send data to server.But some times the ajax call works repeatedly.I called the ajax function in button click as

$(document).on("click", "#btnContinue", function() {
    $.ajax({
        url: "ExcelColDesptn.php",
        data: data,                           
        type: 'post',
        success: function(response) {}
    });

HTML:

<button id="btnContinue" name="btnContinue" class="btn btn-primary ">Continue </button> 

I use firebug to fix it, it shows enter image description here

I don't know why it happens. Here 'ExcelColDesptn.php' is called 3 times and 'SaveExcelToServer.php' is called 4 times. Sometimes it works exactly 1 time. Any help?


回答1:


The function you have, is this binding in another function? Which is called multiple times? Because this is a LIVE binding which means, the binding exists even if the content is update.

So I expect the following:

  • You use ajax to update content
  • #btnContinue is inside an HTML element which is updated by Ajax?
  • You call the function to add a new binding to the button
  • The button gets an extra click binding
  • so the more times you update your ajax, the more times the upload is executed. Because of the way you bind your click.

Solution:

  1. Make it a normal binding $("#btnContinue").on("click", fn)
  2. Put your binding only in document ready, and not in a function which is called multiple times
  3. use $("#btnContinue").off("click") before your new binding (which is the most ugly solution)



回答2:


please use your code like this

$('#btnContinue').Click(function() {
    $.ajax({
        url: "ExcelColDesptn.php",
        data: data,                           
        type: 'post',
        success: function(response) {}
    });
});


来源:https://stackoverflow.com/questions/26925611/ajax-call-fired-multiple-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!