我正在使用JSON向我的服务器发送数据和从服务器发送数据,但通常我一次发送一个数据,现在我想:
从表中检索所有行(mysql数据库) --> php将其放入JSON数组+ callback -> javascript检索它并通过循环遍历数据将其显示出来。
下面是我的javascript(jQuery):
$.getJSON(domain_path + 'generate.php?table=' + tbname + '&callback=?', function(data) {
});正如您所看到的,这里有table=作为表名。这是让php知道从哪个表中提取数据。
但是对于php部分,我不确定使用什么来生成JSONP数组。
<?php
//connects to database
include 'connect.php';
$tbname = mysql_real_escape_string($_GET['table']);
$callback = $_GET['callback'];
//some mysql commands
//after mysql commands
//i would use this to output data but this is only for one line of data.
$output = array('error'=>'0');
$out_string = json_encode($output);
echo $callback.'('.$out_string.');';
?>Mysql表结构:
表名:用户
名称、链接、电子邮件
如何从users表中获取所有行,这些行包含他们的姓名、链接和电子邮件,并将其放入JSON数组中。
如何使用javascript(jquery)将其显示出来?它是否在使用javascript中的for函数
发布于 2012-04-03 16:22:56
用PHP打印出JSON数组:
$query = mysql_query("SELECT * FROM ".$tbname."");
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
print json_encode($rows);捕获并循环结果为jQuery:
$.getJSON(domain_path + 'generate.php?table=' + tbname + '&callback=?', function(data) {
$.each(data, function() {
$.each(this, function(k, v) {
/// do stuff
});
});
});首先,每个循环遍历您的行/对象;第二个循环遍历您的属性/列。
发布于 2012-04-03 16:36:14
您使用命名回调的方法是完全错误的,回调功能已经由jQuery提供了-请注意,您已经将一个空函数作为最后一个参数传递给了getJSON()?这就是你的回调。
你想做这样的事情:
PHP:
<?php
//connects to database
include 'connect.php';
// mysql_real_escape_string() doesn't help, we need to do something like this:
if (strpos($_GET['table'], '`') !== FALSE) {
header('HTTP/1.1 400 Bad Request');
exit;
}
// Build/make the query
$query = "SELECT * FROM `{$_GET['table']}`";
if (!$result = mysql_query($query)) {
header('HTTP/1.1 500 Internal Server Error');
exit;
}
// Fetch the returned data into an array of objects:
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = (object) $row;
}
// Send the final data back as JSON
exit(json_encode($output));Javascript:
$.getJSON(domain_path + 'generate.php?table=' + tbname, function(data, status, xhr) {
// First check the response is a success:
if (xhr.status != 200) {
console.log('Server responded with error code '+xhr.status);
return;
}
// Now iterate over the data:
$.each(data, function(key, item) {
// Do something with the data here, for example:
console.log('Name: '+item.name+', Link: '+item.link+', Email: '+item.email);
});
});https://stackoverflow.com/questions/9989289
复制相似问题