您在这里搜索了问题,但找不到任何内容。我是编写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;`
答案 0 :(得分:19)
不要echo
该行,将其保存在变量中。构造一个简单的数组
$response = array(
'html' => $the_line_you_wanted_to_echo,
'jsobject' => $the_object_you_were_going_to_send_back
);
并将其发回(通过json_encode
)。
另外,你不需要json2.js,jQuery有一个优秀的JSON解析器。
您可以像$.get( 'your/url', { params : here }, success, 'JSON' );
已更改以匹配您新引入的迭代。
for ($x = 0, $num_rows = mysql_num_rows($result); $x < $num_rows; $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']))
);
}
$html = "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
echo json_encode(array( 'comments' => $comments, 'html' => $html ));
然后,在你的javascript中,你有
function success( parsedObject ){
parsedObject.html; // "<h1 style..."
parsedObject.comments; // an array of objects
parsedObject.comments[0].name
+ " on " + parsedObject.comments[0].datetime
+ " said \n" + parsedObject.comments[0].comment; // for example
}
答案 1 :(得分:5)
如上所述,只需将您想要的所有数据放回到数组中并对其进行编码。
<?php
echo json_encode(array(
'html' => $html,
'foo' => $bar,
'bar' => $baz
));
?>
同样如你所说,你不需要json2.js。您可以通过将数据类型指定为json来使用jQuery的任何ajax函数解析JSON数据。
$.ajax({
type: 'POST',
url: 'path/to/php/script.php',
dataType: 'json',
data: 'foo=bar&baz=whatever',
success: function($data) {
var html = $data.html;
var foo = $data.foo;
var bar = $data.bar;
// Do whatever.
}
});
编辑几乎是Horia所说的。我能看到的唯一其他变体是你想要同一个数组中的所有内容。
例如:
PHP:
<?php
// You have your comment array sent up as you want as $comments
// Then just prepend the HTML string onto the beginning of your comments array.
// So now $comments[0] is your HTML string and everything past that is your comments.
$comments = array_unshift($comments, $your_html_string);
echo json_encode($comments);
?>
jQuery的:
$.ajax({
type: 'POST',
url: 'path/to/php/script.php',
dataType: 'json',
data: 'foo=bar&baz=whatever',
success: function($comments) {
// Here's your html string.
var html = $comments[0];
// Make sure to start at 1 or you're going to get your HTML string twice.
// You could also skip storing it above, start at 0, and add a bit to the for loop:
// if x == 0 then print the HTML string else print comments.
for (var x = 1; x < $comments.length; x++) {
// Do what you want with your comments.
// Accessed like so:
var name = $comments[x].name;
var comment = $comments[x].comment;
var datetime = $comments[x].datetime;
}
}
});
答案 2 :(得分:0)
您可能对jLinq感兴趣,这是一个允许您查询Javascript对象的Javascript库。示例查询将是:
var results = jLinq.from(data.users)
.startsWith("first", "a")
.orEndsWith("y")
.orderBy("admin", "age")
.select();
jLinq支持查询嵌套对象和执行连接。例如:
var results = jLinq.from(data.users)
.join(data.locations, //the source array
"location", //the alias to use (when joined)
"locationId", // the location id for the user
"id" // the id for the location
)
.select(function(r) {
return {
fullname:r.first + " " + r.last,
city:r.location.city,
state:r.location.state
};
});