【发布时间】:2018-08-05 14:51:56
【问题描述】:
我正在尝试将 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 发送整个数据)。
【问题讨论】:
-
@PhilS 不,刚刚尝试过,它仍然给出空输出。
-
你用过
FormData吗? -
@Sakezzz 是的,这有效,但我仍然想知道这里有什么问题。
标签: javascript php json ajax fetch