[英]How can I use ajaxComplete applied to a XMLHttpRequest
我正在執行異步請求,以使用XMLHttpRequest()加載json文件。 我需要先等待請求完成,然后再進行其余操作。
我看到ajaxComplete()應該做到這一點,但是我無法將其應用於我的實際代碼並使之正常工作。
在這里,我設置了通過異步請求調用json的函數
function ajaxCall(){
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
arrayImages = JSON.parse(xmlhttp.responseText);
output(arrayImages);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
在這里我叫那個功能
ajaxCall();
現在我希望它完成
do other things
有什么幫助嗎?
謝謝!
您有兩個選擇。
一個承諾
function ajaxCall(){
return new Promise(function(success){
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
arrayImages = JSON.parse(xmlhttp.responseText);
output(arrayImages);
success();
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
});
}
然后,您可以在完成后做一些事情
ajaxCall().then(function(){
// Do stuff after
});
或者您可以使用回調...
function ajaxCall(callback){
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
arrayImages = JSON.parse(xmlhttp.responseText);
output(arrayImages);
callback();
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
然后像這樣做東西
ajaxCall(function(){
// do stuff after
});
ajaxComplete
是jQuery庫的一部分。 它僅將自身綁定到jQuery ajax請求。 盡管這些通常包裝XMLHttpRequest,但是當您手動使用XMLHttpRequest時,它們無法觸摸XMLHttpRequest。
要在響應返回后運行一些代碼,您需要等待適當的事件。 您已經在這里這樣做了:
if(xmlhttp.readyState==4 && xmlhttp.status==200){
在收到響應后,將要運行的代碼放入該if語句中。
如果要使ajaxCall
可重用,則將一個函數作為參數傳遞給它,然后在if
語句內部調用該函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.