简体   繁体   English

提取API不发送POST数据

[英]Fetch api doesn't send POST data

I'm trying the Fetch API for the first time and I'm trying to POST a variable to a PHP script. 我第一次尝试使用Fetch API,并且尝试将变量发布到PHP脚本。 I did this same this with jQuery.ajax() which did work. 我使用确实起作用的jQuery.ajax()进行了同样的操作。

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

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

This returns to me Undefined index 'name' . 这返回给我Undefined index 'name'

What am I doing wrong? 我究竟做错了什么?

The working jQuery code: 可用的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 );
});

The PHP Script: 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 有效的jQuery代码

data: { name : name} 数据:{名称:名称}

… so when you used jQuery you send WWW URL Form Encoded data (the default jQuery encoding). …因此,当您使用jQuery时,您将发送WWW URL表单编码数据(默认的jQuery编码)。

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

… but when you switched to fetch, you also converting the object to JSON. …但是当您切换到提取时,您还将对象转换为JSON。

JSON is not WWW URL Form Encoded! JSON没有经过WWW URL编码!

You, presumably, haven't rewritten the PHP to expect JSON, and are probably trying to read from $_POST (which is empty, because PHP doesn't support JSON encoded requests by default). 您大概没有重写PHP以期望使用JSON,并且可能正试图从$_POST读取(此为空,因为PHP默认情况下不支持JSON编码的请求)。

You can construct a FormData object which will be encoded in a way that PHP will parse by default. 您可以构造一个FormData对象,该对象将以PHP默认解析的方式进行编码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM