我正在尝试使用数组中的json将多个变量从php文件发送回ajax。 php文件中的代码完美运行,并且应该像我的数据库一样完成所有操作。 但是当我在ajax中添加dataType:"json"时,php文件中就没有任何事情发生了。 我google了一下,有些人提到它可能是一个浏览器问题,但到目前为止它无法在firefox,chrome或IE中使用。 我正在使用最新版本的jQuery。
这是在php内部发生的事情:
//Create variables and update database
echo json_encode(array("id" =>"$realid","un" =>"$username","date" =>"$date"));
?>
这是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
}
});
我对此毫无头绪,任何建议都将不胜感激!
检查firebug / net面板中的ajax响应,看看你的服务器是什么。
contentType HTTP标头可能会有所帮助
我怀疑返回的内容不是严格的JSON - 检查PHP之前或之后的空格,或文件中不应该存在的任何其他内容(提示:在json_encode之后使用'die')。 如果未在JQuery中指定dataType,则成功=获取响应。 当你这样做时,成功=获得一个有效的响应....同时检查你的PHP版本,我似乎记得json_encode在早期版本中被窃听过。
常见问题是浏览器在JSON之前打印"别的东西",无论是可读的还是不可读的(不可见的)char。尝试做这样的事情:
//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));
?>
现在,所有补充数据(在JSON之前)将被丢弃,你应该让它工作......
谢谢,这就行了!
我相信如果您使用dataType,您应该使用contentType,"JSON的官方Internet媒体类型是application / json"。
.ajax(
{
url: 'UpdateComments.php',
type: 'POST',
contentType:"application/json",//note the contentType defintion
dataType:"json",
data:
{
type:"add",
comment: $("#comment").val(),
id: videoID
},
success: function (data)
{
//Get the data variables from json and display them on page
}
});
尝试将错误处理程序定义为$ .ajax调用的一部分
$.ajax({
...,
error: function(xml, error) {
console.log(error);
}
});
然后检查调试控制台是否有任何可以帮助您诊断问题的错误。
我不会使用dataType,如果它导致你的问题,我个人也没有使用过对象作为数据值之前可能与它有关系吗?
无论如何,我已经调整了主要的ajax例程,我希望这会有所帮助。
$.ajax(
{
url: 'UpdateComments.php',
type: 'POST',
data:
{
type:"add",
comment: $("#comment").val(),
id: videoID
},
success: function (response)
{
//Get the data variables from json and display them on page
var data = $.parseJSON(response);
alert(data.id);
}
});
如果在jQuery中设置dataType,则实际设置Content-Type头属性。也许,在您的PHP脚本中,您需要将此MIME类型声明为已接受。您是否注意到代码在您发出请求时是否进入了PHP脚本?如果它在Firefox,Chrome或IE中不起作用,我怀疑这是一个浏览器问题。
要获得更好的AJAX请求透视图,请订阅ajaxBeforeSend(不确定事件名称是否正确检查jQ docs)事件并记录xhr对象。