我正在寻找动态内容来填充由 JSON 回调的记录,下面的脚本非常适合从数据库中提取记录,经过一番考虑,如果假设数据库表包含超过 10000 条记录,这是一种方式将回调记录限制为 20 条,直到滚动到达列表视图数据角色的末尾,然后将从列表末尾拉出另外 20 条记录,依此类推。
PHP 从数据库中查询记录:
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "root";
$password = "";
$database = "test";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT employeeNumber, firstName, email, jobTitle FROM employees ORDER BY firstName";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
Ajax 填充返回的记录:
$(document).ready(function() {
// load JSON data
var output = $('#output');
$.ajax({
beforeSend: function() { $.mobile.loading('show'); },
complete: function() { $.mobile.loading('hide'); },
url: 'pool.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 10000,
success: function(data, status){
$.each(data, function(i, item){
var i = i + 1;
var employee = '<li><a href="#indexPage"><img src="images/head.jpg" />'
+ '<h3>#' + i + " " + item.firstName + '</h3>'
+ '<p>' + item.employeeNumber + '<br>'
+ item.email + '<br>'
+ item.jobTitle + '</p></a></li>';
output.append(employee);
});
},
error: function(){
output.text('Error loading data!');
}
});
});
结果将附加在此处:
<div data-role="content">
<div class="content-primary">
<ul data-role="listview" id="output" data-filter="true"></ul>
</div>
</div>
请多多指教,谢谢。