无法通过POST请求将json数据发送到服务器

时间:2018-08-05 14:51:56

标签: javascript php json ajax fetch

我正在尝试将json数据发送到服务器(使用提取API和PHP作为服务器端语言)。我的服务器端代码非常简单:

<?php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: PUT, GET, POST");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

    print_r($_POST);
?>

现在,当我像这样简单地使用"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"发送请求时:

fetch("http://localhost:80/test.php", {
    method: 'POST',
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: "a=b"
})
.then(function(response){
    return response.text();
})
.then(function(text){
    console.log(text);
})

一切正常,输出为:

Array
(
    [a] => b
)

现在,当我想发送相同的内容但使用JSON时:

fetch("http://localhost:80/test.php", {
    method: 'POST',
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: JSON.stringify({"a":"b"})
})
.then(function(response){
    return response.text();
})
.then(function(text){
    console.log(text);
})

我将整个数组的奇怪输出作为键:

Array
(
    [{"a":"b"}] => 
)

现在,当我在访存调用中将内容类型更改为:"application/json"时,输出将完全丢失,并且我得到一个空数组:

Array
(
)

你能告诉我原因是什么吗?以及如何获得理想的结果。 (使用JSON发送整个数据)。

3 个答案:

答案 0 :(得分:1)

您的JSON应该类似于:
Authenticator

然后在您的PHP中:
JSON.stringify({a: 'Text Value', b: 1})

在解码之前,PHP无法理解JSON。

答案 1 :(得分:1)

将内容类型设置为application/json

fetch('http://localhost:80/test.php', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({a: 'b'})
});

并且服务器端应该能够解码(没有$_POST,而没有表单的后字段):

$array = json_decode(file_get_contents('php://input'));
echo '<pre>'.print_r($array, true).'</pre>';

test.php应该同时发送内容类型标头和JSON:

header('Content-type: application/json; charset=utf-8');

答案 2 :(得分:1)

您在下面进行编码:

fetch("http://localhost:80/test.php", {
    method: 'POST',
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: JSON.stringify({"a":"b"})
})
.then(function(response){
    return response.text();
})
.then(function(text){
    console.log(text);
})

应写为:

fetch("http://localhost:80/test.php", {
    method: 'POST',
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: {"a":"b"}
})
.then(function(response){
    return response.text();
})
.then(function(text){
    console.log(text);
})

注意: body: JSON.stringify({"a":"b"})已更改为body: {"a":"b"}

相关问题