【发布时间】:2014-06-08 21:54:57
【问题描述】:
所有这些以前都有效,我没有改变任何东西,现在它没有。我有两个以 id="live_title" 和 id="live_game" 命名的元素。 AJAX 的目的是更新它们。
我的 jQuery:
var tytul = function getTitle(){
$.ajax({
type : 'GET',
dataType: 'json',
url : 'ajax/getTitle.php',
success : function(data) {
for (var prop in data) {
$('#live_'+prop).html(data[prop]);
}
}
});
}
setInterval( tytul, 10000 );
在 Firebug 中看到的 AJAX 响应:
{"title":"Some title title...","game":"Name of the game"}
PHP 代码发送的东西:
header('Content-Type: application/json');
// creating assoc array here
echo json_encode(array( 'title' => $title, 'game' => $game));
JavaScript 控制台为空。
当我在浏览器中访问ajax/getTitle.php 时,没有错误,并且显示的内容与在 Firebug 中正常显示的内容相同。响应给出了正确的标题(它是“Content-Type: application/json”)。
我已经添加了
error : function(data) {
alert(data);
}
到我的.ajax() 函数。它弹出[object Object]。对于alert(data.title) 或alert(data['title']) 它是undefined
【问题讨论】:
-
你是不是在php文件中将header设置为json?
-
如果将 URL 放入浏览器会得到什么?
-
PHP脚本的响应码是什么?如果是错误代码,则不会调用成功处理程序,即使输出是有效的 json。
-
移除
var data = $.parseJSON(data);,jQuery 会为你解析 JSON (dataType: 'json')。对对象调用$.parseJSON不起作用。 -
@Forien:查看文档:api.jquery.com/jquery.ajax。传递给
error回调的参数不是来自服务器的响应。它是jqXHR对象,其中包含有关错误的更多信息。因此data.title当然会返回undefined。使用console.log而不是alert。
标签: javascript php jquery ajax