这很简单,我让它在2天前工作,但现在我无法找到如何获得一些价值观。我认为我的主要问题是我在循环数组时不知道何时使用[]。
我希望有人可以指出我的问题是什么;
jquery post script;
var mydata = JSON.stringify(desktopicons);
$.post(themeUrl + '/modules/module-save-desktop.php', {
data: desktopicons
}).error(function() {
$('#desktop').append('<div id="jsoninfo">Failed to save desktop.</div>');
}).complete( function() {
$('#desktop').append('<div id="jsoninfo">Desktop for ' + username + ' saved succesfully.</div>');
});
json文件;
[{\"myicons\":[{\"icon\":[{\"rel\":\"#\",\"id\":\"icon1\",\"class\":\"bookmark desktop-icon ui-draggable\",\"title\":\"bookmark\"}]},{\"icon\":[{\"rel\":\"#1\",\"id\":\"icon2\",\"class\":\"bookmark desktop-icon ui-draggable\",\"title\":\"bookmark1\"}]}]}]
jQuery get json;
$.ajax({
type: 'GET',
url: userDesktopJson,
async: false,
dataType: 'json',
success: function(data){
var jsondata = $.parseJSON(data);
$('#desktop').append('<div id="jsoninfo">Data loaded.</div>');
var myicons = jsondata['myicons'];
$.each(myicons, function() {
alert('found!');
});
},
error: function() {
$('#desktop').append('<div id="jsoninfo">Failed to load desktop.</div>');
}
});
它加载文件但我似乎无法从中获取值。
修改
好的,所以现在我无法从每个功能里面的图标中获取ID或标题或其他内容,我不明白
$.each(myicons, function() {
var iconid = this.id;
var rel = this.rel;
var title = this.title;
var iconclass = this.class;
$('<div />', {
'id': iconid,
}).addClass(iconclass).attr('rel', rel).appendTo('#desktop');
$('<div />', {
class: 'icon-title desktop-icon-title'
}).text(title).appendTo(iconid);
});
答案 0 :(得分:1)
删除var jsondata = $.parseJSON(data);
,因为您已设置dataType:'json'
。
然后将var myicons = jsondata['myicons'];
更改为var myicons = data[0].myicons[0];
$.ajax({
type: 'GET',
url: userDesktopJson,
async: false,
dataType: 'json',
success: function(data) {
$('#desktop').append('<div id="jsoninfo">Data loaded.</div>');
var myicons = data[0].myicons[0];
$.each(myicons, function() {
alert('found!');
});
},
error: function() {
$('#desktop').append('<div id="jsoninfo">Failed to load desktop.</div>');
}
});
同时从json数据中删除\
[{"myicons":[{"icon":[{"rel":"#","id":"icon1","class":"bookmark desktop-icon ui-draggable","title":"bookmark"}]},{"icon":[{"rel":"#","id":"icon2","class":"bookmark desktop-icon ui-draggable","title":"bookmark"}]}]}]
如果您想从中获取每个ID,请尝试
$.ajax({
type: 'GET',
url: userDesktopJson,
async: false,
dataType: 'json',
success: function(data) {
$('#desktop').append('<div id="jsoninfo">Data loaded.</div>');
var myicons = data[0].myicons;
$.each(myicons, function() {
console.log(this.icon[0].id);
});
},
error: function() {
$('#desktop').append('<div id="jsoninfo">Failed to load desktop.</div>');
}
});
答案 1 :(得分:0)
你得到一个数组,所以你应该改成它:
var myicons = jsondata[0]['myicons'];