javascript - jquery将来自url的json对象存储在javascript变量中

标签 javascript jquery json

如何使用 .getJSON() 函数将 json 对象保存为 JavaScript 变量?

var js = 
$.getJSON(url, 
    function(data) {...}
);

我需要 function(data) {...} 回调吗?

var 看起来像普通的 json 格式(就像 python 中的字典?)

{"query":{"count":1,"created":"2014-07-18", ...

最佳答案

您需要先声明变量,然后在 success 函数中分配值,如下所示:

var js;
$.getJSON(url, 
    function(data) {
        js = data;
        // or use your data here by calling yourFunction(data);
    }
);

编辑:

如果您的代码类似于以下内容,那么它可能无法工作:

var js;
$.getJSON(url, 
    function(data) {
        js = data;
        // or use your data here by calling yourFunction(data);
    }
);
$("div").html(js);

这是因为 $.getJSON() 是一个异步函数。这意味着下面的代码将继续执行,而无需等待 $.getJSON 完成。相反,您需要在 success 函数中使用变量,如下所示:

var js;
$.getJSON(url, 
    function(data) {
        // the code inside this function will be run,
        // when the $.getJSON finishes retrieving the data
        js = data;
        $("div").html(js);
    }
);

关于javascript - jquery将来自url的json对象存储在javascript变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24817590/

相关文章:

javascript - 使用带有 take 和 delay 的 runSaga 进行测试

javascript - 在 For in 循环中渲染复选框并在 Vue JS 中绑定(bind)它们的值

javascript - 回调无法正常工作node.js

javascript - i-- 和 i = i-1 的评估不一样

javascript - 邮件至 : add users dynamically to same email

java - 类似于 GSON in Jackson for arrays

javascript - 保持建议框相对于输入字段

javascript - 如何在不更改 html 的情况下使用 jquery 删除 <textarea> 中内容之前的多余空格

php - 如何将数值转换为字符串?

java - 当我将 json 发送到 spring Controller 时出现 415 Unsupported Media Type