我在班上制作了一个数组,但我想用json创建它。但我不能这样添加。
var myclass = {
test:0,
testbis:0,
thirdtest:JSON.parse($.getJSON("my/path/to/json"))
};
和我的json
{"1":"first","2":"second","3":"third"}
我想在创建对象“myclass”时创建它。我该怎么办呢?
答案 0 :(得分:2)
由于在AJAX调用成功之前数据不可用,您应该在成功回调中创建对象:
$.getJSON("my/path/to/json", function(data) {
var myclass = {
test: 0,
testbis: 0,
// Notice that you don't need JSON.parse here because the $.getJSON
// method will already do this for you
thirdtest: data
};
// now you could use the myclass instance here.
});