javascript - PHP 后端与 JS xHTMLRequest 前端

标签 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;
    }
}

如何让这个函数返回响应值?

最佳答案

您可以使用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/

相关文章:

php - 如何在 Kohana 中获取 Controller 和操作名称

javascript - 如何在jquery中添加id?

javascript - 当我需要同时过滤多个内容时,如何调用一次过滤器?

javascript - 请求的资源上不存在 'Access-Control-Allow-Origin' header —尝试从 REST API 获取数据时

PHP 如果未定义,则在 GET 值上设置默认值

php - 在 MySQL 中获取最后插入的 IDS

javascript - jQuery - 定位 href 指向图像的 <a> 元素

javascript - 时间码有百分之几吗?

PHP GD 锐度滤镜

php - Wordpress 侧边栏搞砸了。为什么?