Ajax 结果显示未定义

Ajax result show undefined

本文关键字:未定义 显示 结果 Ajax      更新时间:2023-09-26

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

所以我收集了这段代码并应用到我的页面中,它只一个接一个地附加"未定义"。

请问我的代码中有什么错误。

在下面,我给出了我的完整轮询脚本和相关文件

我的表名称:更新侧

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(); 
});

上行新.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;
}

将 ajax 请求数据类型添加为 "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);
        }
    });

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

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

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

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

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

应该是:

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