在 JS 中,我想创建一个向后端 PHP 服务器发出 xHTMLRequest 的函数,问题是我希望 JS 等待响应,否则它将显示“未定义”。
function xhrReq(method, args) {
let xhr = new XMLHttpRequest();
xhr.open(method, 'http://localhost/example/php/example.php');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(args);
xhr.onreadystatechange = ()=> {
if(xhr.readyState == 4) {
return xhr.response;
}
}
如何让这个函数返回响应值?
最佳答案
您可以使用fetch在异步函数中:
(async () => {
try {
//const args = ...;
var headers = new Headers();
headers.append("Content-Type", "application/x-www-form-urlencoded");
const response = await fetch('http://localhost/example/php/example.php', {
method: 'POST', // or other
headers,
body: args
});
} catch (err) {
//process error
}
})()
或者你可以 promise 你的功能:
function xhrReq(method, args) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, 'http://localhost/example/php/example.php');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(Error(`XHR request failed. Error code: ${xhr.statusText}`));
}
};
xhr.onerror = function() {
reject(Error('There was a network error.'));
};
xhr.send(args);
});
}
并在异步函数中使用它(或使用 Promise)来获取响应。
关于javascript - PHP 后端与 JS xHTMLRequest 前端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59166144/