echojson_encode没有来自服务器的响应,但常规echo有响应吗



我正试图从本地主机向开发站点发出测试请求,我只需要测试一些代码。我正在尝试制作一个非常简单的fetch请求,它只是以json的形式回显响应。这是跨站点请求,正在禁用cors。问题是,当我试图用echo json_encode回应时,回应会说:
failed to load response data: No data found for resource with given identifier
但是,如果我只是在echo json_encode之前启动一个常规的echo 'a';,两个响应现在都会显示在网络选项卡中。我使用的是Chrome。这里有一些代码:

fetch('https://example.com/test.php',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
mode: "no-cors",
body:JSON.stringify({
test:'1'
})
})
.then(r => r.json())
.then(function(r){
console.log(r)
})

在php中,我只拥有它,它什么也不返回。

if(empty($_POST)){
$_POST = json_decode(file_get_contents("php://input"), true);
}
echo json_encode(['200'=>'Got it']);

如果我这样做:

echo 'x';
echo json_encode(['200'=>'Got it']);

我的响应看起来像:(浏览器检测为正确的json(

x{'200':'Got it'}

你有什么想法吗?我已经试着把所有这些放在我的php文件中:

ini_set('display_errors', 1);
header("Cache-Control: no-cache, must-revalidate");
header("Content-type: application/json");
header("Access-Control-Allow-Origin: *");
json_last_error_msg();

有什么想法吗?非常感谢。

您可以回显数组或对象:

$obj = new stdClass();
$obj->message = 'gotit';
$obj->code = 200;
echo json_encode($obj); // prints {"message":"gotit","code":200}
$arr = Array('200' => 'gotit');
echo json_encode($arr); // prints {"200":"gotit"} 

查看这是否适用于

<?php
$content = trim(file_get_contents("php://input"));
echo json_encode(['200'=>'Got it']);
exit();

最新更新