首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有JS xHTMLRequest前端的PHP后端

带有JS xHTMLRequest前端的PHP后端
EN

Stack Overflow用户
提问于 2019-12-04 06:10:29
回答 1查看 57关注 0票数 1

在JS中,我想创建一个函数来创建一个后端PHP服务器的xHTMLRequest,问题是我想让JS等待响应,否则它将显示'undefined‘。

代码语言:javascript
复制
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;
    }
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-04 06:18:10

您可以在异步函数中使用fetch

代码语言:javascript
复制
(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
  }
})()

或者你可以简化你的函数:

代码语言:javascript
复制
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)来获得响应。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59166144

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档