如何在列表视图中显示json数据?
问题描述:
我想使用json调用来检索php页面中的数据,并使用jquery mobile在listview中显示它。我能够检索数据,并能够显示在列表中,但我面临的问题是: 我的数据流这样在php文件中: ([{“id”:“1”,“name”:“Big Ben“,”latitude“:”51.500600000000“,”longitude“:” - 0.124610000000“},{”id“:”4“,”name“:”Hadrian's Wall“,”纬度“:”55.024453000000“ : “2.142310000000”},{ “ID”: “2”, “名称”: “巨石”, “纬度”: “51.178850000000”, “经度”: “ - 1.826446000000”},{ “ID”: “3”, “名称”:“多佛白崖”,“纬度”:“51.132020000000”,“经度”:“1.334070000000”}]);如何在列表视图中显示json数据?
当我在列表中显示它时,它只显示在列表的一行中。我怎样才能将数据显示在与他们的“id”相关的独立行中?
答
var i;
for(i = 0; i < data.length; i+=1) {
// do whatever here, the id is in data[i].id
console.log(data[i].id);
}
既然你提到你正在使用jQuery移动,也许你会追加<li>
元素列表视图,在这种情况下,你会使用你的<ul data-role=listview>
的.append
方法。
编辑:根据你的评论,你的每个函数改成这样:
$.each(data, function(i, item) {
$('ul').append('<li><h1>' + item.name + '</h1><p>' + item.latitude + '<br>' + item.longitude + '</p></li>');
});
而且从HTML代码中删除<li><a id="output"> </a></li>
。
但是,如果页面上有多个<ul>
元素,它将不起作用,因此建议在正确的<ul>
元素上设置id
。
答
$(document).ready(function(){
$(document).bind('deviceready', function(){
//Phonegap ready
onDeviceReady();
});
var output = $('#output');
$.ajax({
url: 'http://samcroft.co.uk/demos/updated-load-data-into-phonegap/landmarks.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<h1>'+item.name+'</h1>'
+ '<p>'+item.latitude+'<br>'
+ item.longitude+'</p>';
output.append(landmark);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
以上我发布了我的代码.. plz请参阅 – Fabre
我应该在哪里提及此代码? – Fabre
你正在使用'.each',所以我真的不知道这是什么问题... –