我使用这个 jQuery 函数通过 Ajax 获取数据:
function addContentPrt(cid){
$.ajax({
url: "<?=parseLink('addContent.php')?>",
type: "POST",
cache: true,
dataType:'json',
data: {id: cid},
success: function(returnedData){
console.log(returnedData);
},
error: function (xhr, tst, err) {
console.log(err);
}
});
}
在接收端:
<?
header("Content-Type: application/json", true);
if(isset($_POST['id'])) {
$id = $_POST['id'];
}
$sql = mysql_query("SELECT * FROM pharmacies WHERE id=$id");
$r = mysql_fetch_array($sql);
echo $r['title'];
echo $id;
?>
echo $id
确实返回到 ajax,但不是 $r['title']
,它在控制台中返回 null
。如果我添加一些像 hello world
的虚拟文本,我会收到一个合成错误 SyntaxError: Unexpected token h {stack: (...), message: "Unexpected token h"}
这可能是什么原因,我能做些什么来解决它?
最佳答案
<?
header("Content-Type: application/json", true);
if(isset($_POST['id'])) {
$id = $_POST['id'];
}
$sql = mysql_query("SELECT * FROM pharmacies WHERE id=$id");
$r = mysql_fetch_array($sql);
echo json_encode('id' => $id, 'title' => $r['title']);
?>
在你的 ajax 成功中:
success: function(returnedData){
console.log(JSON.parse(returnedData));
},
关于javascript - 数据未从 ajax POST 返回,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29487674/