【问题标题】:AJAX "success" not calledAJAX“成功”未调用
【发布时间】: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


【解决方案1】:

尝试先控制您的 ajax 响应,然后再进行进一步操作

var tytul = function getTitle(){
$.ajax({
    type : 'GET',
    dataType: 'json',
    url : 'ajax/getTitle.php',
    success : function(data) {
       //if successfull           
       console.log(data);

    },
    error:function(data){
    //if error
    console.log(data);
    }
  });
}
setInterval( tytul, 10000 );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2013-02-14
    • 2012-02-16
    • 2015-05-07
    • 1970-01-01
    相关资源
    最近更新 更多