【问题标题】:jquery store json object from url in javascript variablejquery将来自url的json对象存储在javascript变量中
【发布时间】:2014-07-18 05:08:07
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • function(data){...}部分是getJSON的回调,data是你会得到的JSON响应。
  • 您的意思是要在JavaScript 变量中接收$.getJSON 返回的数据?

标签: javascript jquery json


【解决方案1】:

你需要先声明变量,然后在成功函数中赋值:

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 完成。相反,您可能希望像这样在成功函数中使用变量:

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);
    }
);

【讨论】:

  • $("div").html(js);不打印到我的 html div 吗?
  • 谢谢。尽管如此,这仍然没有在 div 中显示任何内容。我想在我的 div 中实际打印出 json 对象。
  • $("div").html(js); 之前您是否尝试添加console.log(js); 以确保$.getJSON 正确检索数据?如果没有,请告诉我打印的内容
【解决方案2】:

假设您希望在 javascript 变量中接收 $.getJSON 返回的 data

var js;

$.getJSON(url, function(data) {
    js = data;
    // you can even pass data as parameter to your target function like myFunct(data);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多