簡體   English   中英

無法使用 POST 請求將 json 數據發送到服務器

[英]Can't sent json data to server with POST request

我正在嘗試將 json 數據發送到服務器(使用 fetch 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"}] => 
)

現在,當我在 fetch 調用中將內容類型更改為: "application/json"時,輸出完全丟失,我得到空數組:

Array
(
)

你能告訴我是什么原因嗎? 以及如何達到預期的結果。 (使用 JSON 發送整個數據)。

將內容類型設置為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');

你的 JSON 應該是這樣的:
JSON.stringify({a: 'Text Value', b: 1})

然后在你的 PHP 中:
print_r(json_decode($_POST));

PHP 無法理解 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);
})

應該寫成:

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"}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM