从 PHP 脚本返回 JSON 和 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2083136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
returning JSON and HTML from PHP script
提问by Dave Kiss
Hi searched through the questions here, but couldn't find anything. I'm new at writing PHP and jQuery, so bear with me.
您好在这里搜索了问题,但找不到任何内容。我是编写 PHP 和 jQuery 的新手,所以请耐心等待。
What I'm trying to do is send an ajax request using jQuery to my script which runs a mysql query on data from my database and serializes it into the JSON format using php's json_encode. The response is then parsed with the available json2.js script. All of this works fine, but I'd also like to return more data other than just JSON from this script.
我想要做的是使用 jQuery 向我的脚本发送一个 ajax 请求,该脚本对我的数据库中的数据运行 mysql 查询,并使用 php 的 json_encode 将其序列化为 JSON 格式。然后使用可用的 json2.js 脚本解析响应。所有这些都很好,但我还想从这个脚本返回更多的数据,而不仅仅是 JSON。
mainly, i'd like to also echo the following line before the json_encode:
主要是,我还想在 json_encode 之前回显以下行:
echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
however, my jQuery is evaluating the entire response during the ajax success, making the json.parse function fail due to the script's return being in an invalid format.
但是,我的 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 + '');
}
does anyone know how i can return the html line as well as the json_encode to use this script for more than just json population?
有谁知道我如何返回 html 行以及 json_encode 以将此脚本用于不仅仅是 json 人口?
thankyou, this website has been wonderful in answering my noob questions.
谢谢,这个网站很好地回答了我的菜鸟问题。
my php:`
我的 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;`
回答by Horia Dragomir
Don't echothe line, save it in a variable. Construct a simple array
$response = array(
'html' => $the_line_you_wanted_to_echo,
'jsobject' => $the_object_you_were_going_to_send_back
);and send that back ( via json_encode) instead.
不要echo行,将其保存在变量中。构造一个简单的数组
$response = array(
'html' => $the_line_you_wanted_to_echo,
'jsobject' => $the_object_you_were_going_to_send_back
);并将其发回( via json_encode)。
Also, you don't need json2.js, jQuery has an excellent JSON parser.
此外,您不需要 json2.js,jQuery 有一个出色的 JSON 解析器。
you can load like this $.get( 'your/url', { params : here }, success, 'JSON' );
你可以这样加载 $.get( 'your/url', { params : here }, success, 'JSON' );
Changed to match your newly introduced iteration.
已更改以匹配您新引入的迭代。
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 ));
then, in your javascript, you have
然后,在你的 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
}
回答by anomareh
As said above just put all the data you want to get back in an array and encode that.
如上所述,只需将您想要返回的所有数据放入一个数组中并对其进行编码。
<?php
echo json_encode(array(
'html' => $html,
'foo' => $bar,
'bar' => $baz
));
?>
Also as said you don't need json2.js. You can parse JSON data with any of jQuery's ajax functions by specifying the data type as json.
也如上所述,您不需要 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.
}
});
EDITPretty much what Horia said. The only other variation I could see is if you wanted everything in the same array.
编辑几乎是 Horia 所说的。我能看到的唯一其他变化是你是否想要同一个数组中的所有内容。
For example:
例如:
PHP:
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:
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;
}
}
});
回答by David Robbins
You might be interested in jLinq, a Javascript library that allows you to query Javascript objects. A sample query would be:
您可能对jLinq感兴趣,这是一个允许您查询 Javascript 对象的 Javascript 库。示例查询将是:
var results = jLinq.from(data.users)
.startsWith("first", "a")
.orEndsWith("y")
.orderBy("admin", "age")
.select();
jLinq supports querying nested objects and performing joins. For example:
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
};
});

