2015-04-01 61 views
1

我使用jQuery load()方法根據添加到輸入字段中的值將內容加載到頁面中。出於某種原因,我一次收到多個ajax調用,所以我所調用的內容在頁面中出現兩次,而不是一次。使用jQuery Ajax load()方法進行多個調用的問題

希望能讓人心動!

這裏是我工作的代碼:

function Acun() { var firstChar = $('#accountnumber').val().charAt(0); if(firstChar != 'x' && firstChar != 'X'){ $('#examplepagecontent').html('<div id="invoice-loader"></div>'); $("#examplepagecontent").load("/product/pay-an-invoice #content"); } else { $('#examplepagecontent').html('<div id="invoice-loader"></div>'); $("#examplepagecontent").load("/product/pay-an-invoice-with-account-z #content"); } }

HTML:

<input type="text" name="Account Number" value="" 
    id="accountnumber" name="accountnumber" onKeyUp="Acun();" maxlength="7"/> 
+0

你是怎麼調用函數Acun的?你有多次調用這個函數的機會嗎? – 2015-04-01 19:03:51

回答

1

要調用每一個使用keyUp功能。這意味着每次輸入一個字符時,當按鈕被擡起時,該功能將運行。

你會想嘗試這樣的事情

var timer; //important to have variable outside the function 
function Acun() { 
    window.clearTimeout(timer); 
    timer = window.setTimeout(function(){ 
     var firstChar = $('#accountnumber').val().charAt(0); 
     if(firstChar != 'x' && firstChar != 'X'){ 
      $('#examplepagecontent').html('<div id="invoice-loader"></div>'); 
      $("#examplepagecontent").load("/product/pay-an-invoice #content"); 
     } 
     else { 
      $('#examplepagecontent').html('<div id="invoice-loader"></div>'); 
      $("#examplepagecontent").load("/product/pay-an-invoice-with-account-z #content"); 
     } 
    },500); //run after a half second of no activity 
} 
+0

感謝您的建議,我試過了您的代碼,但內容仍然出現兩次。我試着刪除'onKeyUp =「Acun();」 '從輸入字段改爲使用下面的按鈕:''但問題仍然存在? – 2015-04-01 19:32:58

+0

也許不是使用html onclick屬性,而是嘗試在Acun函數之外的某處添加腳本'$('button [name =「button」]')。on('click',Acun);'如果沒有'噸工作,有可能點擊事件被應用兩次的地方? – nexusgx 2015-04-01 19:52:57

1

您在onKeyUp="Acun();"事件調用Acun()功能。每次用戶按下按鈕時都會發生此事件。

您應該檢查其他請求是否有待處理,並且不要求新的請求,或者您可以檢查輸入的長度爲textbox,並以最大請求作出請求。