最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Populate .data() with $.getJSON() - Stack Overflow

programmeradmin1浏览0评论

I am trying to populate $('div').data() through JSON. It works fine with JQuery.parseJSON but not with $.getJSON.

// works as expected
$('div').data('dat', { xmin: '-10', xmax: 40 });
$('div').data('dat', jQuery.parseJSON('{"bbx" : {"xmin" : "-10", "xmax" : "40"}}'));

// doesnt work
$('div').data('dat', $.getJSON("init.php", function(json) {return(json);}));

I am trying to populate $('div').data() through JSON. It works fine with JQuery.parseJSON but not with $.getJSON.

// works as expected
$('div').data('dat', { xmin: '-10', xmax: 40 });
$('div').data('dat', jQuery.parseJSON('{"bbx" : {"xmin" : "-10", "xmax" : "40"}}'));

// doesnt work
$('div').data('dat', $.getJSON("init.php", function(json) {return(json);}));
Share Improve this question edited Dec 12, 2012 at 11:16 A. Wolff 74.4k9 gold badges97 silver badges157 bronze badges asked Dec 12, 2012 at 11:14 johannesjohannes 14.5k6 gold badges42 silver badges51 bronze badges 4
  • It's asynchronous, so no, that won't work? On the other hand, setting the data inside the callback function of getJSON would work just fine, but not the other way around. – adeneo Commented Dec 12, 2012 at 11:18
  • $.getJSON() is async see Sudhir's answer – A. Wolff Commented Dec 12, 2012 at 11:19
  • Maybe dollar sign is used by another framework? Try jQuery.getJSON – arttronics Commented Dec 12, 2012 at 11:20
  • This might help: SO Answer – arttronics Commented Dec 12, 2012 at 11:33
Add a ment  | 

4 Answers 4

Reset to default 5

you could do:

$.getJSON("init.php", function(json) {
    $('div').data('dat', json);
});

Probably because getJSON is an async operation. The original statement is now out of scope by the time your success function executes.

Can you not do it this way ?

$.getJSON("init.php", function (json) {
    $('div').data('dat', json);
});

getJSON is an ajax call which is asyncronous, so the function itself doesn't return anything, it just calls the appropriate callback, so you could do this instead:

$.getJSON("init.php", function(json){
    $('div').data('dat', json);
})

Note: $.get will retrieve the JSON as a string and won't parse it unlike getJSON, so if you want to store the JSON as a string then use $.get. Storing the parsed object will work as well (by using getJSON).

You can also store data in array format:

$.getJSON('init.php', function(data) {
    var items = [];

    $.each(data, function(key, val) {
        items.push(val);
    });

    $('div').data('dat', items)
});
发布评论

评论列表(0)

  1. 暂无评论