通过 fetch 检索值(将值从 javascript 发送到 php 文件)

retrieving value through fetch (sending values from javascript to php file)

我是新手,不知道 Ajax。

我正在尝试将数据从 JavaScript 文件(node.js 服务器)发送到 PHP 文件(Apache 服务器)。

我通过 JavaScript 发送 2 个 JSON 值作为 "a" 和 "b".

我的代码是这样的。

fetch('http://localhost/react_task/react-webpack-boilerplate/php/api.php', {
  method: 'post',
  body: JSON.stringify({
    a: 2,
    b: 1
  })
}) .then(function(response) {
  if (response.status >= 200 && response.status < 300) {
    return response.text()
  }
  throw new Error(response.statusText)
})
.then(function(response) {
  console.log(response);
})

有人能告诉我如何在我的 PHP 文件中检索 a 和 b 的值吗? 我正在与 react.js

合作

您可以通过 PHP 中的 $_POST 参数获取发布值。

为了测试,将这些行粘贴到您的 api.php

if($_POST["a"]=="2" && $_POST["b"]=="1")
{
    echo "I posted 2 and 1";
}

现在 response.text() 应该 return I posted 2 and 1.

因为您要通过 POST 请求传递 JSON blob,所以您需要在尝试读取其中的数据之前对 JSON 进行解码。您还应该使用 PHP 的 Filter Functions 来安全地检索用户输入。

下面是一些示例代码(未经测试):

<?php
$input = file_get_contents('php://input');
$input = json_decode($input);
$filtered_a = filter_var($input->a, FILTER_SANITIZE_NUMBER_INT);
$filtered_b = filter_var($input->b, FILTER_SANITIZE_NUMBER_INT);

echo "Safely received numeric inputs: a: {$filtered_a} b: {$filtered_b}";
?>

可以在文档的 introduction page 中找到有关使用过滤器函数的方式和原因的更多详细信息。