2012-04-30 122 views
-1

我想寫使用jQuery的post.I傳遞的參數,以ajax.php並獲得josn數據添加用戶註釋代碼,如下:AJAX與特定值後返回的HTML標籤

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

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

我的問題是jQuery的返回許多不敬html標籤wihth JSON數據作爲下面

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

解決這個問題最簡單的方法是什麼? 在此先感謝!

+1

發佈您的ajax.php完整代碼?它有問題。 – thecodeparadox

+1

是不是$ classobj> add_comment這應該是$ classobj - > add_comment? – KBN

+0

你還有別的'echo'聲明嗎?嘗試評論'echo json_encode($ ajax);'並且看看你得到了什麼結果。或者嘗試在'echo'後面加上'exit'並查看結果。 – pomeh

回答

0

如果您的ajax.php文件包含任何樣式或HTML,那麼您在執行AJAX請求時將返回該數據。從你的ajax端點中刪除任何樣式或HTML。一個簡單的方法是在JSON編碼之後(如果HTML之後有HTML),或者完全刪除它,則可以使用exit()die()

還有,記得json_encode($ajax)之前包括下面的代碼:

header('Content-Type: application/json'); - 這將確保它始終是公認的JSON對象。我知道Chrome肯定有問題,推斷你發回的實際上是JSON!