2012-06-10 96 views
0

这个问题已经被问及很多问题,并且在过去的3天中经历了许多不同的'解决方案',我都无法工作。JQuery Mobile为ListView解析JSON

我有一个巨大的JSON文件,一些150k条目,我想在JQuery Mobile中查看为ListVIew。 (我将使用过滤器实际使用数据)

我想出的最好的是这个

<!DOCTYPE html> 
<html> 
<head> 
<title>Test</title> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<link rel="stylesheet" href="css/jqm-docs.css" /> 
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" /> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script> 
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script> 




</head> 

<body> 
    <div data-role="page"> 
    <div data-role="content"> 
     <div id="output"> 
      <ul data-role="listview" data-inset="true" data-filter="true"> 

      </ul> 
     </div> 
    </div> 
</div> 


<script type="text/javascript"> 
     //simulating the JSON coming from the server 
var json = '["City1","City2","City3"]'; 
//jQuery getJSON will do this step 
var data = $.parseJSON(json); 

//and this is your code 
$.each(data, function (index, value) { 
     $('#output').children('ul').append('<p>'+value+'</p>').listview('refresh'); 
}); 

</script> 

</body> 
</html> 

如果我删除.listview(“刷新”),则所有三个JSON条目列在同一个ListView字段中。我显然希望他们分开。

任何人都可以建议如何做到这一点?

与感谢

回答

2

为了使用$.parseJSON首先你需要有适当的JSON string format

,所以我想你的变量

var json = '["City1","City2","City3"]'; 

应该更像:

var json = '{"city":"City1"},{"city":"City2"},{"city":"City2"}'; 

然后前要将其转换为JSON,您宁愿先将其拆分为

var jsonSplit = json.split(','); 

,并转换为JSON每一个单独部分的阵列

var data = new Array(), i; 
for(i in jsonSplit){ 
if(jsonSplit[i].length){ //remove last empty element after .split() 
    data[i] = $.parseJSON(jsonSplit[i]); 
} 
} 

然后在你可以操纵data作为一个JavaScript对象

1

你缺少li元素。

$.each(data, function (index, value) { 
     $('#output').children('ul').append('<li><p>'+value+'</p></li>').listview('refresh'); 
}); 
1
$.each(data, function (index, value) { 
     $('#output').children('ul').append('<li><p>'+value+'</p></li>').listview('refresh'); 
}); 

删除根据你是什么列表视图(刷新)在这里做,你不需要每次刷新。如果你是通过说php等动态添加它的话......你需要在最后刷新。

$.each(data, function (index, value) { 
     $('#output').children('ul').append('<li><p>'+value+'</p></li>'); 
});