2012-12-20 51 views
1


Ajax事件後調用javascript的其餘部分

我正在嘗試爲輸入字段執行自動完成功能。

僞代碼

<input type="text"/> 

<script> 
var ref,resp;//Global Variables 

$('input').live('keyup',function(){ 
    /* Get the input offset, so that list container can be palced at the bottom of the input once get the values through Ajax call */ 

    ajaxCall(); 

/*** 
    Here I want to write a code to create a div and place the values with in the div and show at the respective input field. 
***/ 

}); 

function ajaxCall(){ 
var ref = new XMLHttpRequest(); 
    ref.open(); 
    ref.readStateChange = function(){ 
    if(ref.readyState == 4 && ref.status ==200) 
     resp = ref.responseText(); 
    } 
    ref.send(); 
} 

</script> 

,我在這裏得到的問題,那就是後Ajax調用應執行一次阿賈克斯readyState爲4和值retrived代碼的一部分。

但是,當readyState爲1(在其他狀態之後未調用它)時,該代碼正在執行,其中未從數據庫中檢索值。讓我無法顯示列表。

:我知道下面的部分可以放在AjaxCall的,但它包含了一些變量,可以在地方設置....

難道我的問題有意義嗎?如果是這樣,可以讓一些機構知道解決方案...

+1

jQuery在XmlHttpRequest上有一個很好的抽象層,即'$ .ajax'函數 –

+0

@Alnitak是的。但正如我所提到的,一些必須在ajax調用之後執行的代碼有一些變量和數據可以在前面的功能可以設置爲只..... –

+0

還不能確定你使用的是什麼版本的jQuery但'.live()'已經被廢棄了,因爲1.4 – wakooka

回答

0

您希望在完成ajax調用後運行的代碼應放在代碼的onSuccess()或onComplete()方法中。

ajaxCall(function(resp) { 


    /*** 
     Here I want to write a code to create a div and place the values with in the div and show at the respective input field. 
    ***/ 
}); 

即..你的代碼必須進來的onComplete()方法,whic將通過Ajax調用的參數返回的這部分數據。

1

你必須調用依賴於AJAX回調過程中的AJAX調用的結果的功能。這只是它是如何:

function ajaxCall(callback) { 
    var ref = new XMLHttpRequest(); 
    ref.open(); 
    ref.readStateChange = function() { 
     if (ref.readyState === 4 && ref.status === 200) { 
      resp = ref.responseText(); 
      callback.call(null, ref.responseText); // invoke the callback here 
     } 
    } 
    ref.send(); 
} 

然後:

ajaxCall(function(resp) { 
    // handle "resp" here 
}); 

儘管如此,請不要重新發明輪子。你最終將得到很難維護的代碼,而且不能跨瀏覽器移植。有很多庫讓AJAX代碼像這樣成爲一個完整的輕鬆方式。我使用jQuery。

+0

我已經將兩個變量傳遞給了這個函數。所以我想通過這個cb,這應該是第一個參數還是最後一個參數? –

+0

@RamaRaoM它可以是任何你想要的。只要你一致,這並不重要。 – Alnitak