嗨在这里通过问题搜索,但找不到任何东西。我在编写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