You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AJAX请求返回JSON属性而非整串值的实现方法咨询

解决AJAX返回JSON字符串无法直接访问属性的问题

问题根源在于你PHP代码里的JSON编码逻辑重复了:你在循环中对每个帖子的数组单独做了json_encode,然后把这些JSON字符串塞进数组,最后又整体编码一次。这就导致返回给前端的是一串JSON字符串组成的数组,而不是对象数组,所以JS里拿到的value是字符串,自然没法直接访问last_id和content属性。

修改PHP代码

只需要去掉循环里的json_encode,直接把关联数组添加到$testyme,最后统一编码整个数组即可:

if ($_POST) { 
    $lastCustomerNewsID = $_POST['lastCustomerNewsID']; 
    $new_posts = sw::shared()->customers_news->getNewForWall($lastCustomerNewsID); 
    $testyme = []; // 提前初始化数组,避免未定义变量警告
    if ($new_posts) { 
        foreach ($new_posts as $new_post) { 
            $content = "<div class='wall_post'>"; 
            $content .= $new_post['message']; 
            $content .= "</div>"; 
            // 直接添加关联数组,不要单独编码
            $testyme[] = [
                "content" => $content, 
                "last_id" => $new_post['id'] 
            ]; 
        } 
    } 
    // 最后统一编码,保留JSON_UNESCAPED_SLASHES避免转义链接斜杠
    echo json_encode($testyme, JSON_UNESCAPED_SLASHES); 
}

前端JS代码(无需修改,直接使用你期望的逻辑)

因为PHP现在返回的是标准的对象数组,$.ajax指定了dataType:"json"会自动解析成JS对象,所以你原本期望的遍历方式可以正常工作:

function checkForNewPosts() { 
    var lastCustomerNewsID = <?php echo $customers_news[0]['id']; ?>; 
    $.ajax({ 
        url: "https://www.example.com/check_for_new_posts.php", 
        method: "post", 
        data:{ lastCustomerNewsID: lastCustomerNewsID }, 
        dataType:"json", 
        success:function(data) { 
            $.each(data, function( key, value ) { 
                $('#wall_posts').prepend(`Id: ${value.last_id}, Content: ${value.content}<br>`); 
            }); 
        } 
    }); 
}

修改后,PHP返回的JSON结构就是你想要的格式:

[
    {
        "content": "<div class='wall_post'>Check it out here: <a href='https://www.example.com/events/trymeguy/'>https://www.example.com/events/trymeguy/</a></div>",
        "last_id": "476"
    },
    ...
]

前端就能直接通过value.last_id和value.content访问对应属性了。

内容的提问来源于stack exchange,提问作者cpcdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:13:22