doyrte8419 2012-04-30 08:29
浏览 29

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

I'm trying to write a code that adds user comment using jquery's post.I passed parameters to ajax.php and received josn data, as the following:

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'
);

on ajax.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);

My problem is the jquery returns many irreverent html tags wihth the json data as the below

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

what is the easest way to solve this problem? Thanks in advance!!

  • 写回答

1条回答 默认 最新

  • drl9940 2012-04-30 08:42
    关注

    If your ajax.php file contains any style or HTML, you will be given that data back when you perform your AJAX request. Remove any styling or HTML from your ajax endpoint. A simple way is to exit() or die() after the JSON encode (if there is HTML after it) or just remove it totally.

    Also, remember to include the following code before json_encode($ajax):

    header('Content-Type: application/json'); - this will ensure it is always recognised as a JSON object. I know Chrome certainly has problems inferring what your sending back is actually JSON!

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c