我正在撰寫一些代碼,其中將有一個函式 (doAjax) 來處理對不同功能的所有請求。這在正常意義上使用(單擊按鈕等)時作業正常,但我試圖在頁面加載時呼叫一些東西來初始化應用程式的狀態。
這是 Ajax 函式:
function doAjax(type, action, data = null){
return new Promise(function(res,rej){
xhr = new XMLHttpRequest();
xhr.open(type, '/inc/functions.php?action=' action, true);
xhr.timeout = 20000;
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (this.status === 200) {
res(xhr);
} else {
console.log("some xhr error occured");
rej("some xhr error happened");
}
};
xhr.send(data);
});
}
以下是一些向此發送請求的函式示例:
/* get file structure of files */
function buildTree(){
doAjax('GET', 'get_files').then(r => {
var res = JSON.parse(r.response);
console.log(res);
/*
the json is processed here and stuff
is displayed on the front end
*/
}
}
/* get user data from database */
function populateShare(){
doAjax('GET', 'social_populate').then(r => {
var res = JSON.parse(r.response);
console.log(res);
/*
again, the json received from the database is
processed and output to the front end
*/
}
}
還要提一下,這些函式也系結了點擊監聽器,所以在后面的應用程式中以及onload中都會用到!
現在,問題是當我嘗試在頁面加載時執行這兩個作為一種初始化函式(設定應用程式準備使用)。如果我運行以下:
function init(){
buildTree();
populateShare();
}
init(); //called later
兩個 console.logs 輸出相同的結果 - 從 social_populate 回傳(從 populateShare() 呼叫)。
所以我的問題最終是是否有任何方法可以在 init() 函式中對函式呼叫進行排隊,等待每個函式完成后再進行下一個?init() 上可能需要呼叫更多的函式,其中一些還涉及 Ajax 請求。
我嘗試了以下在另一個執行緒中找到的方法 - 但不幸的是回傳相同的結果:
async function initialise(){
try {
const p1 = buildTree();
const p2 = populateShare();
await Promise.all([p1, p2]);
} catch (e) {
console.log(e);
}
}
我知道我可以從后端加載整個批次并以一個巨大的 JSON 回傳,但我更好奇是否可以實作上述目標!我覺得我已經進入了某種同步請求死亡回圈,或者我在這里遺漏了一些明顯的東西!
另外,請不要使用jQuery!
謝謝!
uj5u.com熱心網友回復:
當您宣告xhr
在每次呼叫時被覆寫的全域變數時,您似乎不小心使用了全域變數。
嘗試 let xhr = new XMLHttpRequest();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/386017.html
標籤:javascript 阿贾克斯 等待 同步 页面加载
上一篇:來自ajax的下拉呼叫api