嗨在這裏通過問題搜索,但找不到任何東西。我在編寫PHP和jQuery方面很新,所以請耐心等待。從PHP腳本返回JSON和HTML
我想要做的是發送一個使用jQuery的ajax請求到我的腳本,該腳本對我的數據庫中的數據運行mysql查詢並使用php的json_encode將其序列化爲JSON格式。然後使用可用的json2.js腳本解析響應。所有這些工作都很好,但我還想從此腳本中返回除JSON之外的更多數據。
主要是,我想也呼應json_encode之前以下行:
echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
然而,我的jQuery是評估阿賈克斯成功在整個響應,使得由於json.parse功能失效該腳本的返回格式無效。
success: function(data) {
//retrieve comments to display on page by parsing them to a JSON object
var obj = JSON.parse(data);
//loop through all items in the JSON array
for (var x = 0; x < obj.length; x++) {
//Create a container for the new element
var div = $("<div>").addClass("bubble").appendTo("#comments");
//Add author name and comment to container
var blockquote = $("<blockquote>").appendTo(div);
$("<p>").text(obj[x].comment).appendTo(blockquote);
var cite = $("<cite>").appendTo(div);
$("<strong>").text(obj[x].name).appendTo(cite);
$("<i>").text(obj[x].datetime).appendTo(cite);
}
$("#db").attr("value", '' + initialComments + '');
}
沒有人知道我可以返回HTML線還有json_encode使用這個腳本的不僅僅是JSON人口多嗎?
謝謝你,這個網站在回答我的noob問題方面一直很棒。
我的PHP:`
for ($x = 0, $numrows = mysql_num_rows($result); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($result);
$comments[$x] = array("name" => stripslashes($row["name"]), "comment" => stripslashes($row["comment"]), "datetime" => date("m/d/Y g:i A", strtotime($comment['datetime'])));
}
//echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
$response = json_encode($comments);
echo $response;`
感謝您的迴應,但我不知道如何實現它,因爲我只需要回聲一次的html,而不是我爲評論創建的for循環。你可以看看我添加到問題中的代碼並指向正確的方向嗎?謝謝! – 2010-01-18 00:08:53
如果你看看我的答案,你可以做同樣的事情,而不使用數組。因此'echo json_encode($ html);'然後在成功函數中,您只需通過'$ data'訪問它。 – anomareh 2010-01-18 00:18:13
謝謝! json_encode數組正是我所需要的。 – 2010-01-19 15:18:43