【问题标题】:How do i get the response text from a php script?如何从 php 脚本中获取响应文本?
【发布时间】:2019-12-16 17:42:08
【问题描述】:

我正在使用 fetch API 将数据发送到 PHP 脚本,该脚本依次处理它并使用 exit() 函数返回一条消息。 当我在下一个工作选项卡下打开开发人员工具时,我可以看到此响应,但我不知道如何在我的 javascript 代码中访问此响应。 这是我的 javascript 代码:

fetch(url, {
      method: 'POST',
      body: formData,
    }).then(response => {
      if (response.status === 200) {
        console.log(this.responseText); //this is the property i'm not sure of
      }
    }).catch( (error) => {
      handleError("you are disconnected");
    });

这是我的 php 代码:

$comment = $_POST['comment'];
$category = $_POST['category'];
$id = $_POST['id'];
if ($comment && $category && $id) {
exit("invalid");
} else ....

【问题讨论】:

  • 变量this.responseText 包含服务器发送的响应文本。您可以使用该变量访问它。
  • @Mike - 你确定吗?看起来像 XMLHttpRequest 的东西,而不是 fetch 的东西:p
  • this.responsetext 返回 undefined :-(
  • 因为 fetch 响应没有 responseText 属性 - 你想到的是 XMLHttpRequest - 这是一种完全不同的动物
  • @JaromandaX 我认为它是一个 XMLHttpRequest。我猜我错了。

标签: javascript php fetch-api


【解决方案1】:

您要查找的是响应的正文。这是一个可读的流,所以你需要处理这个承诺。

例子:

fetch(url, {
  method: 'POST',
  body: formData,
})
  .then(response => response.json()) // read the response stream as JSON
  .then(data => console.log('Here is your actual response body', data))
  ... whatever else you want to do here...

在上面的示例中,流被读取为 JSON。对于您的特定用例,text() 方法可能更合适。

【讨论】:

  • response.json() ... 或 response.text()(以及其他类似 arrayBuffer、blob、formData)如果 API 不返回 JSON(没有迹象表明它确实如此) - 事实上,没有迹象表明OP 的 API 返回的所有内容
  • @JaromandaX 谢谢 :) 根据习惯回答哈哈,但你说得对,有很多方法可以使用。
  • text() 方法实际上运行良好,谢谢!
猜你喜欢
  • 2013-07-13
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-16
相关资源
最近更新 更多