[英]Jquery appending list after localStorage JSON parsing
在過去的一個小時里,這一直讓我頭疼。 基本上,我檢查localStorage以查看是否具有JSON字符串的緩存版本。 如果這樣做,我將其加載並將其轉換回JSON對象。 如果沒有緩存的版本,則使用Ajax並從服務器獲取JSON對象。
無論哪種方式,在獲得JSON對象后,我都會調用parseDirectory函數,該函數將迭代JSON數據並創建html。 解析后,它將HTML附加到我的頁面。 我已經測試了這兩種方法,並且它們都成功創建了HTML。因此,我知道JSON數據很好。 我加載了JSON數據的緩存版本,並在JSONLint中運行了它,它是有效的。
奇怪的是,當我加載Cached JSON對象時,jQuery append函數不起作用。 當我使用Ajax調用下載它時,它確實起作用。 這是代碼
function loadPhoneList()
//clearCache("Directory");
// Check if we have a cached version available
if (isJSONCached("Directory")==true)
{
// We have a cached version of this module. Let's load that up
var JSONobj = loadCachedJSON("Directory");
parseDirectory(JSONobj);
}
else
{
$.ajax({
dataType: 'jsonp',
jsonp: 'jsonp_callback',
url: 'http://www.myserver.com/directory.php',
data: 'cname=' + customername,
success: function (data)
{
// Cache this new JSON info
cacheJSON("Directory", data );
// Parse the received JSON data
parseDirectory(data);
},
error: function (errormsg)
{
alert(errormsg);
}
});
}
// Parse the JSON and create our content
function parseDirectory(JSONobj)
{
var model_list = '';
for (var i=0;i<JSONobj.directory_data.length;i++)
{
model_list += '<li class="item item-text-wrap"><p>' + JSONobj.directory_data[i].Name + '</p><p>' + JSONobj.directory_data[i].Number + '</p></li>';
}
alert(model_list);
$("#directoryList").append(model_list);
}
}
HTML是
<div class="content-nopadding" >
<div class="list">
<div class="item item-divider">
<center>Phone Directory</center>
</div>
<ul class="list" id="directoryList">
<li class="filler"></li>
</ul>
</div>
</div>
**編輯。 添加了cacheJSON代碼**
// Used to store a cached version of a JSON string in localStorage by Key value
function cacheJSON( key, json )
{
// Need to convert the JSON object to a string so we can store it
var JSONtoStr = JSON.stringify(json);
window.localStorage.setItem(key,JSONtoStr);
}
一切在JSFiddle中都運行良好。由於我是在移動設備上進行開發的,因此原因是在運行JS之前未加載DOM。 我添加了一個onDeviceReady事件處理程序來解決該問題。
感謝您的光臨!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.