javascript - 在创建对象时将 getJSON 转为数组

标签 javascript jquery json


我在类中创建了一个数组,但我想用 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/

相关文章:

javascript - 无法在主 javascript 中访问 c​​offeescript 类

javascript - 想要使用 jQuery 调整单个 div 内的图像大小,图像被 chop

javascript - 是否可以根据 JS 变量包含 CSS 文件?

javascript - 数组和JSON之间是否存在混合数据结构?

javascript - Scrolltop 水平起点

javascript - 如何向国际 Google 网站添加域切换选择器?

javascript - 如何使用 Ionic 返回文本框的值?

javascript - JQuery删除不删除指定的div

javascript - html5 + XML + JS 的动态页面?

java - 使用 GSON 将 Java 接口(interface)转换为 JSON 字符串,而不将序列化封装在 JSON 对象中?