带有JS xHTMLRequest前端的PHP后端

时间:2019-12-03 22:10:29

标签: javascript php

在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;
    }
}

如何使该函数返回响应值?

1 个答案:

答案 0 :(得分:0)

您可以在异步函数中使用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
  }
})()

或者您可以使您的功能丰富化:

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)以获取响应。