我正在尝试动态创建一个简单的select
,其中包含基于某些约束的对象属性option
。
当我的JSON是脚本的一部分时,一切正常。
代码
$(document).ready(function(){
/*$.getJSON('input.json',function(data){
alert('inside');
});*/
/*$.getJSON("inputjson.json", function(data){
// I have placed alert here previously and realized it doesn't go into here
console.log("datd");
console.log(JSON.stringify(data,null,4));
});*/
var jsonList =
{
"json_data" : {
"data" : [
{
"data" : "A node",
"metadata" : { id : 23 },
"children" : [ "Child 1", "A Child 2" ]
},
{
"attr" : { "id" : "li.node.id1" , "level" : "3" , "name" : "Ragini" },
"data" : {
"title" : "Long format demo",
"attr" : { "href" : "#" }
}
},
{
"attr" : { "id" : "li.node.id1" , "level" : "3" , "name" : "Rag" },
"data" : {
"title" : "Long format demo",
"attr" : { "href" : "#" }
}
},
{
"attr" : { "id" : "li.node.id1" , "level" : "4" , "name" : "Skyrbe" },
"data" : {
"title" : "Long format demo",
"attr" : { "href" : "#" }
}
}
]
}
}
var newObject = jsonList.json_data.data;
var listItems= "";
$form = $("<form></form>");
$('#form_container').append($form);
var $selectContainer = $("<select id=\"selectId\" name=\"selectName\" />");
for (var i = 0; i < jsonList.json_data.data.length; i++)
{
if(jsonList.json_data.data[i].hasOwnProperty("attr") && jsonList.json_data.data[i].attr.level == 3)
{
listItems+= "<option value='" + jsonList.json_data.data[i].attr.name + "'>" + jsonList.json_data.data[i].attr.name + "</option>";
}
}
$($selectContainer).html(listItems);
$($form).append($selectContainer);
});
但是当我尝试将JSON放入单独的.json文件并使用$.getJSON
时,我没有取得任何成功。基本上,控制从未进入过。
这是我为$.getJSON
$.getJSON('input.json',function(data){
console.log(JSON.stringify(data,null,4));
});
有人可以指出我的错误。
干杯, 戒日
答案 0 :(得分:3)
您正在尝试在getJSON调用完成之前创建select元素。将其余代码放入getJSON函数的回调函数中,如下所示:
$.getJSON("inputjson.json", function(data){
// I have placed alert here previously and realized it doesn't go into here
console.log("datd");
console.log(JSON.stringify(data,null,4));
var newObject = jsonList.json_data.data;
var listItems= "";
$form = $("<form></form>");
$('#form_container').append($form);
// etc
});
另请注意,您有一个拼写错误和一些不需要的引号 - console.log("datd");
应为console.log(data);
(除非您确实只想将“&dat;&#39;”这个词放入您的日志中)
答案 1 :(得分:3)
您的jsonList
变量具有有效的对象文字,因此当它直接包含在您的脚本中时,它将起作用。但是该对象文字不是有效的JSON,因此当它包含在单独的文件中以便通过$.getJSON()
进行检索时它将无法工作 - 在JSON中需要引用所有属性名称。所以这一行:
"metadata" : { id : 23 },
......需要:
"metadata" : { "id" : 23 },
修复后,您需要将处理jsonList
的代码移动到您提供给$.getJSON()
的回调函数中:
$.getJSON('input.json',function(data){
// do all processing here
});
将来,如果您在使用JSON时遇到问题,可以使用此网站验证JSON:http://jsonlint.com/
答案 2 :(得分:0)
如果您的JSON文件有任何语法错误,它将不返回任何内容。 $ .getJSON是一个jquery ajax别名,它在后台使用$ .parseJSON()(http://api.jquery.com/jQuery.getJSON/)。 看,JSON语法与Javascript文字对象语法略有不同,所以如果你错过了一个变量中的引用,就像你在下面所做的那样,它将无法按预期工作。
"metadata" : { id : 23 }