Vâng đây là giải pháp của tôi và làm việc hoàn hảo:
PHP:
<?php
ini_set('magic_quotes_gpc', false);
header('Content-type: text/plain');
//DB connection credentials
$dbhost = 'hostname';
$dbuser = 'database_username';
$dbpass = 'database_password';
$dbname = 'database_name';
// allow cross-browser acces
header('Access-Control-Allow-Origin: *');
// query SQL
$sql = "do your DB query SELECT what ever here";
//do our thingies withouth hacks (SQL Injection, etc)
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->query("set names utf8");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$json_export = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
// return JSON format DATA
echo '{"items":'. json_encode($json_export) .'}';
} catch(PDOException $e) {
// return error
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
HTML ListView:
<div data-role="page" id="myPage"><div data-role="content" id="myContent">
//my HTML list tag
<ul data-role="listview" id="myList"></ul>
</div></div>
JAVASCRIPT
//trigger script on show page
$('#myPage').live('pageshow',function (event) {
//get our JSON data
$.getJSON('path_to_your_php_json_generator_file_declared_upper',function(data){
//append our JSON data to a variable
var json_entries = data.items;
//for each JSON data, append it to our list as one element
$.each(json_entries,function(index,entry){
$('#myList').append('<li><a href="#">' + entry.title + '</a></li>');
//assuming we have a field named "title" in JSON data
});
//refresh the list for layout (style) loading
$('#myList').listview('refresh');
});
});
Và đây là cách bạn điền một danh sách trên jQuery Mobile với dữ liệu JSON được tạo bởi một tệp php. Bạn có thể điều chỉnh loại tập lệnh này cho mọi trình thông dịch JSON trong mã jQuery của bạn, ngay cả với các thông số (id, danh mục, v.v.)!
Hy vọng nó sẽ giúp cách này hay cách khác!
Hãy thử 'console.log() 'trên' dữ liệu' đối tượng để xem nếu nó là chèn dom hoặc json nhận được rằng đang có vấn đề –
kiểm tra trong bảng điều khiển firebug lỗi ... – Rafay
Nó có nghĩa bạn có lỗi trong tập lệnh PHP và bạn không nhận được phản hồi JSON. –