获取 api 不发送 POST 数据

Fetch api doesn't send POST data

我第一次尝试 Fetch API,我正在尝试 POST 一个变量到 PHP 脚本。我用 jQuery.ajax() 做了同样的事情,它确实有效。

var myRequest = new Request('invoeren.php', {method: 'POST', body: JSON.stringify({name: name})});

fetch(myRequest).then(function(response) {
    console.log(response);
});

这个returns给我Undefined index 'name'

我做错了什么?

工作jQuery代码:

$.ajax({
    url: "invoeren.php",
    method: "POST",
    data: { name : name}
}).done(function( msg ) {
    console.log(msg);
}).fail(function( jqXHR, textStatus ) {
    alert( "Naam is niet ingevoerd door een probleem: " + jqXHR );
});

PHP脚本:

try {
    $dbh = new PDO('mysql:host=localhost;dbname=ajaxoef', $user, $pass);
    $stmt = $dbh->prepare('INSERT INTO names(name) VALUES (:name)');
    $stmt->bindParam(':name', $name);

    $name = json_decode($_POST['name']);
    $stmt->execute();

    echo "Naam is ingevoerd.";
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

The working jQuery code

data: { name : name}

… 所以当你使用 jQuery 你发送 WWW URL 表单编码数据(默认 jQuery 编码)。

body: JSON.stringify({name: name})

… 但是当你切换到 fetch 时,你也将对象转换为 JSON.

JSON 不是 WWW URL 表单编码!

你大概没有重写 PHP 来期望 JSON,并且可能正在尝试从 $_POST 读取(它是空的,因为 PHP默认情况下不支持 JSON 编码请求。

您可以构造一个 FormData 对象,它将以 PHP 默认解析的方式进行编码。

var body = new FormData;
body.append("name", name);
//...
body: body