我在类中创建了一个数组,但我想用 json 创建它。但我不能这样添加这个。
var myclass = {
test:0,
testbis:0,
thirdtest:JSON.parse($.getJSON("my/path/to/json"))
};
和我的 json
{"1":"first","2":"second","3":"third"}
我想在创建对象“myclass”时创建它。请问我该怎么做?
最佳答案
由于在 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.
});
关于javascript - 在创建对象时将 getJSON 转为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34594985/