21

我正在尝试使用fetch()API POST 方法来获取 PHP 中的 POST 数据。

这是我尝试过的:

var x = "hello";
fetch(url,{method:'post',body:x}).then(function(response){
    return response.json();
});

PHP:

<?php
if(isset($_GET['x']))
{
    $get = $_GET['x'];
    echo $get;
}
?>

这个对吗?

4

7 回答 7

37

这取决于:

如果你想$_GET['x'],你需要在查询字符串中发送数据:

var url = '/your/url?x=hello';

fetch(url)
.then(function (response) {
  return response.text();
})
.then(function (body) {
  console.log(body);
});

如果您愿意$_POST['x'],您需要将数据发送为FormData

var url = '/your/url';
var formData = new FormData();
formData.append('x', 'hello');

fetch(url, { method: 'POST', body: formData })
.then(function (response) {
  return response.text();
})
.then(function (body) {
  console.log(body);
});
于 2016-01-08T17:29:43.527 回答
29

显然,当使用 Fetch API 向 PHP 服务器发送数据时,您必须处理与您习惯的请求稍有不同的请求。

您正在“发布”或“获取”的数据不会在超级全局变量中可用,因为此输入不是来自 a multipart-data form或 anapplication/x-www-form-urlencoded

您可以通过读取特殊文件:来获取数据php://input,例如使用file_get_contents('php://input')然后尝试使用json_decode().

你可以在这里读更多关于它的内容:

https://codepen.io/dericksozo/post/fetch-api-json-php

于 2018-03-15T03:57:37.567 回答
9

我使用MDN的 postData 函数:

/**
 * send_body___receive_response.js
 *
 * Can of-course be in <script> tags in HTML or PHP
 */

async function postData( url='', data={ } ) {
  // *starred options in comments are default values
  const response = await fetch(
    url,
    {
      method: "POST", // *GET, POST, PUT, DELETE, etc.
      mode: "same-origin", // no-cors, *cors, same-origin
      cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
      credentials: "same-origin", // include, *same-origin, omit
      headers: {
        "Content-Type": "application/json",  // sent request
        "Accept":       "application/json"   // expected data sent back
      },
      redirect: 'follow', // manual, *follow, error
      referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
      body: JSON.stringify( data ), // body data type must match "Content-Type" header
    },
  );

  return response.json( ); // parses JSON response into native JavaScript objects
}

const data = {
  'key1': 'value1',
  'key2': 2
};

postData( 'receive_body___send_response.php', JSON.stringify( data ) )
  .then( response => {
    // Manipulate response here
    console.log( "response: ", response ); // JSON data parsed by `data.json()` call
    // In this case where I send entire $decoded from PHP you could arbitrarily use this
    console.log( "response.data: ", JSON.parse( response.data ) );
  } );

您可以只发布数据,但我希望收到成功的响应。

/**
 * receive_body___send_response.php
 */

/* Get content type */
$contentType = trim($_SERVER["CONTENT_TYPE"] ?? ''); // PHP 8+
// Otherwise:
// $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';

/* Send error to Fetch API, if unexpected content type */
if ($contentType !== "application/json")
  die(json_encode([
    'value' => 0,
    'error' => 'Content-Type is not set as "application/json"',
    'data' => null,
  ]));

/* Receive the RAW post data. */
$content = trim(file_get_contents("php://input"));

/* $decoded can be used the same as you would use $_POST in $.ajax */
$decoded = json_decode($content, true);

/* Send error to Fetch API, if JSON is broken */
if(! is_array($decoded))
  die(json_encode([
    'value' => 0,
    'error' => 'Received JSON is improperly formatted',
    'data' => null,
  ]));

/* NOTE: For some reason I had to add the next line as well at times, but it hadn't happen for a while now. Not sure what went on */
// $decoded = json_decode($decoded, true);

/* Do something with received data and include it in response */
// dumb e.g.
$response = $decoded['key2'] + 1; // 3

/* Perhaps database manipulation here? */
// query, etc.

/* Send success to fetch API */
die(json_encode([
  'value' => 1,
  'error' => null,
  'data' => null, // or ?array of data ($response) you wish to send back to JS
]));
于 2020-09-22T06:26:10.930 回答
2

显示如何使用FormData使用 fetch api 添加两个数字的工作示例。

对于每个操作,您最好有不同的FormData和自己的字段。

HTML:

<html>
<head></head>

<body>

<div id="numbers_addition">
    <input type="text" id="num1" placeholder="First Number">
    <input type="text" id="num2" placeholder="Second Number">
    <button type="button" onclick="addMyNumbers()">Add</button>
    <p id="result"></p>
</div>

<script id="script_add">

    function addMyNumbers()
    {
        let num1=document.getElementById("num1").value;
        let num2=document.getElementById("num2").value;
        opAddNumbers(num1, num2);
    }

    const frmAddNumbers = new FormData(); // create single instance
    frmAddNumbers.set('cmd', "add_numbers"); // this cmd will not change
    frmAddNumbers.set('first_number', "");
    frmAddNumbers.set('second_number', "");

    function opAddNumbers(num1, num2) {
        frmAddNumbers.set('first_number', num1);
        frmAddNumbers.set('second_number', num2);

        fetch('./cmd.inc.php', {method: 'POST', body: frmAddNumbers})
        .then(res => res.json()) // res.text()
        .then(res => displayResult(res))
        .catch(e => console.error('Error, opAddNumbers(), ' + e))
    }

    function displayResult(response)
    {
        console.log(response);
        document.getElementById("result").innerHTML = `Result = ${response["result"]}`;
    }

</script>

</body>
</html>

PHP(' cmd.inc.php '):

<?php

$cmd=$_POST['cmd'];

switch ($cmd) {
    case "add_numbers":
        $num1=$_POST['first_number'];
        $num2=$_POST['second_number'];
        $result = array("result" => $num1 + $num2);
        $output = json_encode($result);
      break;
  }

echo $output;
于 2021-03-22T11:29:48.940 回答
1

如果碰巧你需要使用现有的服务器,它是用 $_POST 编码的,并且期望来自普通表单的参数,而不是编码为 JSON,你可以使用 formdata,这完全是为了模拟一个表单。

let fd = new FormData();
fd.append("var1", val)
fd.append("var2", "Hello World");
fetch('/servers/server.php', {method: "POST", body: fd})

这样,您的服务器将收到来自普通表单输入字段的 POST 字段。

$var1 = $_POST['var1']; $var2 = $_POST['var2'];
于 2021-06-03T21:10:35.453 回答
0

请记住$_POST,在 PHP 中只抓取一个formData()urlSearchParams()数据,对于其他所有类型的数据,尤其是从其他文件或外部 api 数据导入的数据,您必须按照这些步骤操作。 脚步:

  1. 用于file_get_contents(php://input)接收php中的数据
  2. json_decode($data) 使用并最终在读取/写入数据库后对其进行解码
  3. 使用 发送响应json_encode($response)

这很简单 :-))

于 2021-03-01T05:02:24.217 回答
0

您可以从 json { foo: "bar", "blah": 1} 构建主体 "foo=bar&blah=1"

async function json_as_post_data() {
  let data = {
    foo: "bar",
    "blah": 1
  }
  return fetch('url-here', {
    method: 'post',
    headers: { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" },
    body: Object.entries(data).map(([k, v]) => { return k + '=' + v }).join('&') // 'foo=bar&blah=1'
  }).then(response => {
    return response.json();
  });
}
console.log(await json_as_post_data());
echo json_encode($_POST);
于 2021-10-07T05:44:11.030 回答