我正在尝试使用数组中的json将多个变量从php文件发送回ajax.php文件中的代码完美运行,并且应该像我的数据库一样完成所有操作.但是当我在ajax中添加dataType:"json"时,php文件中就没有任何事情发生了.我google了一下,有些人提到它可能是一个浏览器问题,但到目前为止它无法在firefox,chrome或IE中使用.我正在使用最新版本的jQuery.
这是在php内部发生的事情:
<?php
//Create variables and update database
echo json_encode(array("id" => "$realid", "un" => "$username", "date" => "$date"));
?>
Run Code Online (Sandbox Code Playgroud)
这是ajax代码:
.ajax(
{
url: 'UpdateComments.php',
type: 'POST',
dataType: "json",
data:
{
type: "add",
comment: $("#comment").val(),
id: videoID
},
success: function (data)
{
//Get the data variables from json and display them on page
}
});
Run Code Online (Sandbox Code Playgroud)
我对此毫无头绪,任何建议都将不胜感激!
常见问题是浏览器在JSON之前打印"别的东西",无论是可读的还是不可读的(不可见的)char.尝试做这样的事情:
<?php
//at the very beginning start output buffereing
ob_start();
// do your logic here
// right before outputting the JSON, clear the buffer.
ob_end_clean();
// now print
echo json_encode(array("id" => $realid, "un" => $username, "date" => $date));
?>
Run Code Online (Sandbox Code Playgroud)
现在,所有补充数据(在JSON之前)将被丢弃,你应该让它工作......