如何在 PHP 中使用 fetch() API POST 方法获取数据? [英] How to grab data using fetch() API POST method in PHP?

查看:31
本文介绍了如何在 PHP 中使用 fetch() API POST 方法获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to use fetch() API POST method in order to grab the POST data in PHP.

这是我尝试过的:

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;
}
?>

这对吗?

推荐答案

视情况而定:

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

If you want to $_GET['x'], you need to send the data in the querystring:

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

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

如果你想$_POST['x'],你需要发送数据为FormData:

If you want to $_POST['x'], you need to send the data as 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);
});

这篇关于如何在 PHP 中使用 fetch() API POST 方法获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆