AJAX post 返回具有特定值的 HTML 标记


AJAX post returns HTML tags with the particular value

我正在尝试编写一个代码,使用 jquery 的帖子添加用户评论。我将参数传递给 ajax.php并接收 josn 数据,如下所示:

var formObjectData = $('#' + form_id).serialize() + '&flag=add_comment'; // all 
$.post(
    'http://192.168.3.3/myblog/ajax.php',formObjectData,
    function(data) {
        if (!data)
            alert("No data");
        else {
            if (data.msg!='')
                $("#add_comment").html(data.msg);
        }
    },
    'json'
);

在阿贾克斯上.php

$cid = $classobj->add_comment($comment,$id); // to add the comment in db and return the comment id
$ajax['msg'] = $msg ? $msg : '';
if ($cid) {
    $ajax['cid'] = $cid;
}
echo json_encode($ajax);

我的问题是jquery返回了许多不敬的html标签,其中包含json数据,如下所示

<html>
    <head>
        <style type="text/css">
        </style>
    </head>
</html>{"msg":"hello","cid":"600"}

解决此问题的最简单方法是什么?提前感谢!!

如果您的 ajax.php 文件包含任何样式或 HTML,则在执行 AJAX 请求时将返回该数据。从 ajax 端点中删除任何样式或 HTML。一个简单的方法是在 JSON 编码之后exit()die()(如果它后面有 HTML),或者完全删除它。

另外,请记住在json_encode($ajax)之前包含以下代码:

header('Content-Type: application/json'); - 这将确保它始终被识别为 JSON 对象。我知道 Chrome 肯定在推断您发回的内容实际上是 JSON 时遇到问题!