Ajax POST JSON 中的请求无效
Ajax POST request in JSON doesn't work
我尝试从 ajax 向 PHP 发送一个 HTTP POST 请求,但是我有一个我不明白的语法错误。
有没有人可以帮助我?
index.php
var key = "keytest";
$.ajax({
url: 'requests.php',
type: 'post',
contentType: 'application/json',
dataType: 'json',
data: '{"uniqueKey" : '+key+'}',
success:function( rep ) {
$('#content').html(rep.content);
},
error:function(a,b,err){
console.log(err);
}
});
requests.php
header('Content-type: application/json');
$uniqueKey = filter_input(INPUT_POST, 'uniqueKey');
$key = "newKey";
$retour = array('key' => $key);
echo json_encode($retour);
不要手动构建 JSON,使用 JSON.stringify
data: JSON.stringify({uniqueKey: key}),
Php 不会填充 $_POST
(INPUT_POST) 当请求主体为 JSON 时,仅适用于 application/x-www-form-urlencoded
或 multipart/form-data
要获得 json,您必须从 php://input
阅读它
$json = file_get_contents('php://input');
$obj = json_decode($json);
$uniqueKey = $obj->uniqueKey;
此外,您的代码仅响应 key
值,但 ajax 请求需要 content
值。您应该将数据类型更改为文本,以查看是否得到您期望的结果。
$.ajax({
url: 'requests.php',
type: 'post',
contentType: 'application/json',
dataType: 'text',
data: JSON.stringify({uniqueKey: key}),
success:function( rep ) {
$('#content').html(rep);
},
error:function(a,b,err){
console.log(err);
}
});
我尝试从 ajax 向 PHP 发送一个 HTTP POST 请求,但是我有一个我不明白的语法错误。 有没有人可以帮助我?
index.php
var key = "keytest";
$.ajax({
url: 'requests.php',
type: 'post',
contentType: 'application/json',
dataType: 'json',
data: '{"uniqueKey" : '+key+'}',
success:function( rep ) {
$('#content').html(rep.content);
},
error:function(a,b,err){
console.log(err);
}
});
requests.php
header('Content-type: application/json');
$uniqueKey = filter_input(INPUT_POST, 'uniqueKey');
$key = "newKey";
$retour = array('key' => $key);
echo json_encode($retour);
不要手动构建 JSON,使用 JSON.stringify
data: JSON.stringify({uniqueKey: key}),
Php 不会填充 $_POST
(INPUT_POST) 当请求主体为 JSON 时,仅适用于 application/x-www-form-urlencoded
或 multipart/form-data
要获得 json,您必须从 php://input
$json = file_get_contents('php://input');
$obj = json_decode($json);
$uniqueKey = $obj->uniqueKey;
此外,您的代码仅响应 key
值,但 ajax 请求需要 content
值。您应该将数据类型更改为文本,以查看是否得到您期望的结果。
$.ajax({
url: 'requests.php',
type: 'post',
contentType: 'application/json',
dataType: 'text',
data: JSON.stringify({uniqueKey: key}),
success:function( rep ) {
$('#content').html(rep);
},
error:function(a,b,err){
console.log(err);
}
});