我正在嘗試為我的登錄表單創建一些驗證,當用戶嘗試提交它時,onsubmit="return checkLoginDetails1();"要么嘗試提交表單,要么添加一些警告等。我遇到的問題是我無法從 AJAX 呼叫中獲得結果由于它是異步的,在 return 陳述句之前 - 有沒有人對此有任何想法?我一直在探索各種類似的帖子,但到目前為止沒有結果。
//This is the Ajax call - returns true or false as expected
function waitForAjax() {
return new Promise(function(resolve,reject){$.ajax({
type: "POST",
url: "login-validation.php",
data: {email: $('#login-email').val(), password: $('#login-password').val()},
success: function (data) {
if(data.exists==="Match"){
resolve(true);
} else {
resolve(false);
}
},
dataType: 'JSON'
});
})
}
function checkLoginDetails(){ //function that would be called in my html
var test = await waitForAjax(); //value is returned true/false as expected.
//previously tried waitForAjax().then(response => {
//if(response === true) {
//return true;
//}
//}); and same with false which did not work as it is not being returned to the
//outer-function
return test;
};
uj5u.com熱心網友回復:
最好在回呼時移動 checkLoginDetails(),只洗掉等待 ajax
$.ajax({
type: "POST",
url: "login-validation.php",
data: {email: $('#login-email').val(), password: $('#login-
password').val()},
success: function (data) {
if(data.exists==="Match"){
resolve(true);
} else {
resolve(false);
}
checkLoginDetails();
},
dataType: 'JSON'
});
uj5u.com熱心網友回復:
請嘗試以下解決方案。在 checkLoginDetails 函式之前添加了 async 關鍵字。await 應該總是伴隨著 async。請閱讀有關 Javascript Promises 的更多資訊,以了解問題的根本原因。
//This is the Ajax call - returns true or false as expected
function waitForAjax() {
return new Promise(function(resolve,reject){$.ajax({
type: "POST",
url: "login-validation.php",
data: {email: $('#login-email').val(), password: $('#login-password').val()},
success: function (data) {
if(data.exists==="Match"){
resolve(true);
} else {
resolve(false);
}
},
dataType: 'JSON'
});
})
}
async function checkLoginDetails(){ //function that would be called in my html
var test = await waitForAjax(); //value is returned true/false as expected.
//previously tried waitForAjax().then(response => {
//if(response === true) {
//return true;
//}
//}); and same with false which did not work as it is not being returned to the
//outer-function
return test;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/399001.html
標籤:javascript 查询 阿贾克斯 异步
下一篇:Jquery回圈遍歷dom的元素
