【发布时间】:2011-01-06 04:33:21
【问题描述】:
您好在这里搜索了问题,但找不到任何东西。我是编写 PHP 和 jQuery 的新手,所以请耐心等待。
我要做的是使用 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 在 ajax 成功期间评估整个响应,导致 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 填充?
谢谢,这个网站很好地回答了我的菜鸟问题。
我的 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;`
【问题讨论】: