我是 AJAX 的新手。我的目標是在 JavaScript 中打開一個 php 檔案。
function checkCorrect(userEntry, solution) {
return fetch("checkSolution.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
},
body: `userEntry=${userEntry}&solution=${solution}`,
})
.then((response) => response.text())
.then((res) => (res))
.catch(err => console.log("checkCorrect: " err));
}
function checkSolution() {
result = checkCorrect(userEntry, solution);
alert(result)
}
我的問題是, checkSolution 中的 alert() 顯示“ [object Promise] ”
而不是來自 php 的真正價值。在php中只有一個
回聲“嗨”;
謝謝,BM
uj5u.com熱心網友回復:
您需要在函式宣告之前使用async以便 JS 知道這是一個異步函式,您還需要使用await來等待 promise 解決。這是一個例子:
function async checkCorrect(userEntry, solution) {
try {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
},
body: `userEntry=${userEntry}&solution=${solution}`,
}
const result = await fetch("checkSolution.php", requestParams)
.then((response) => response.text())
.then((res) => (res))
return result;
} catch(e) {
handleYourError(e);
}
}
function checkSolution() {
result = checkCorrect(userEntry, solution);
alert(result)
}
uj5u.com熱心網友回復:
實際上fetch是異步的。我不知道。就我而言,我正在尋找同步方法。
在我的情況下, XMLHttpRequest是正確的方法。
這是解決方案:
function checkCorrect(userEntry, solution) {
var ret_value = null;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
ret_value = xmlhttp.responseText;
}
}
xmlhttp.open("POST","checkSolution.php",false);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("userEntry=" userEntry "&solution=" solution);
return ret_value;
}
xmlhttp.open() 的第三個引數是重要的部分:
如果真 = 異步,如果假 = 同步
謝謝,BM
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/461021.html
標籤:javascript php 阿贾克斯
上一篇:Ajax呼叫后腳本無法正常運行
