【问题标题】:Use response from getJson globally全局使用 getJson 的响应
【发布时间】:2016-09-21 18:19:39
【问题描述】:

当页面加载时我想得到一个json:

$.getJSON(_routes['salesInAMonthJS'], { month: "September 2016" }).then(
    function(d){
        console.log(d);
    }
);

这个

$.getJSON(_routes['salesInAMonthJS'], { month: "September 2016" });

还给我

{"9":{"name":"alex lloyd","country":"Germany","antiquity":"new client","amount":"0.0 USD"},"10":{"name"
:"asdasdsadasda dasda","country":"Afghanistan","antiquity":"new client","amount":"0.0 USD"},"11":{"name"
:"Alex Lloyd","country":"American Samoa","antiquity":"new client","amount":"0.0 USD"},"12":{"name":"alex
 lloyd","country":"Aruba","antiquity":"new client","amount":"0.0 USD"},"5":{"name":"surgeon bueno","country"
:"Spain","antiquity":"renewal","amount":"2686.97 USD"}}

但是,当用户单击按钮时,我想显示存储在 d 中的数据

例如:

$(document).on("click ", ".tick", function(e) {
    e.preventDefault();
    $.each(d, function(i, item) {
        &("div.container").append(d[i].name);
    });
});

但这似乎不起作用,知道我做错了什么吗?谢谢

【问题讨论】:

  • &("div.container") 是 $("div.container") 的拼写错误。
  • 你有一个变量范围的问题。 d 是 $.getJSON 回调函数的本地,你不能在另一个函数中访问它。

标签: jquery json getjson


【解决方案1】:

这样的?

$.getJSON(geocodingAPI, function(json) {
  $.json = json;
});

$('button').on('click', function() {
  alert($.json.status)
});

http://jsfiddle.net/eywpvyrr/1/

【讨论】:

    【解决方案2】:

    d 的作用域只是回调函数。您可以将点击绑定移到其中,以便您可以访问它。

    $.getJSON(_routes['salesInAMonthJS'], { month: "September 2016" }).then(function(d){
        $(document).on("click ", ".tick", function(e) {
            e.preventDefault();
            $.each(d, function(i, item) {
                $("div.container").append(d[i].name);
            });
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 2012-05-14
      相关资源
      最近更新 更多