Ajax结果显示未定义

时间:2014-12-23 12:33:54

标签: javascript jquery ajax

我想通过像facebook这样的关注者来显示用户更新的ajax轮询。

所以我收集这些代码并在我的页面中应用,它只是一个接一个地附加'undefined'。

我的代码中有什么问题。

在下面,我提供完整的民意调查脚本和相关文件

我的表名:updateside

id - work_id - parent_id - from_id - to_id - sub - detail - img - created
..........................................................................

AI - work_id, parent_id etc. all data submit by user post form

我的JavaScript

function waitForMsg(){

    $.ajax({
        type: "GET",
        url: "upsidenew.php",
        async: true, 
        cache: false, 
        timeout:50000, 
        success: function(data){ 
            if(data) {
               $("#updatetime").append('<div class="upbox1">' + data.detail + '</div>');
            }
            setTimeout(
                waitForMsg, 
                1000 
            );
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            addmsg("error", textStatus + " (" + errorThrown + ")");
            setTimeout(
                waitForMsg, 
                15000);
        }
    });
}

$(document).ready(function () {
    waitForMsg(); 
});

upsidenew.php

$parent = //collect from other query
date_default_timezone_set('Asia/Dhaka');
$timestamp = date("M j, y; g:i a", time() - 2592000);

$u = mysqli_query($dbh,"SELECT * FROM updateside WHERE `parent_id`='".$parent."' AND `created` > '".$timestamp."' ORDER BY created DESC") or die(mysqli_error($dbh));
$response = array();
while ($row = mysqli_fetch_array($u)) {
    $response['from_id'] = $row['from_id'];
    $response['parent_id'] = $row['parent_id'];
    $response['to_id'] = $row['to_id'];
    $response['sub'] = $row['sub'];
    $response['detail'] = $row['detail'];
    $response['img'] = $row['img'];
    $response['time'] = $row['created'];

    ?><script><?php echo '(Content-Type: application/json)';?></script><?php
    echo json_encode($response);
    exit;
}

3 个答案:

答案 0 :(得分:0)

将您的ajax请求dataType添加为“dataType:'json'”

$.ajax({
        type: "GET",
        url: "upsidenew.php",
        async: true, 
        cache: false, 
        timeout:50000, 
        dataType: 'json'
        success: function(data){ 
        if(data) {
           $("#updatetime").append('<div class="upbox1">' + data.detail + '</div>');
        }
            setTimeout(
                waitForMsg, 
                1000 
            );
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            addmsg("error", textStatus + " (" + errorThrown + ")");
            setTimeout(
                waitForMsg, 
                15000);
        }
    });

答案 1 :(得分:0)

如果你没有将ajax调用显式的数据类型设置为json,你需要用以下结果解析结果:

jsondata = $.parseJSON(data);
alert(jsondata.detail);

所示

http://api.jquery.com/jquery.ajax/

答案 2 :(得分:0)

如果您要返回JSON,则不应输出echo json_encode($response)以外的任何内容。这一行:

?><script><?php echo '(Content-Type: application/json)';?></script><?php

应该是:

header('Content-type: application/json');