I has something like this:
<div id="content"></div>
and JS:
function getData(id) {
$.getJSON('url/to/jsondata',{id: id}, function(data) {
/** append some data to div#content **/
$('#content').data('key', 'value');
});
then I want to get data of #content in script:
$(document).ready(function() {
getData(1); // run getData with some id
console.log($('#content').data('key'));
});
Problem is console.log not run after callback of getJSON finish, so i get a undefined value in log. Which is right way to make it work? Thank!
I has something like this:
<div id="content"></div>
and JS:
function getData(id) {
$.getJSON('url/to/jsondata',{id: id}, function(data) {
/** append some data to div#content **/
$('#content').data('key', 'value');
});
then I want to get data of #content in script:
$(document).ready(function() {
getData(1); // run getData with some id
console.log($('#content').data('key'));
});
Problem is console.log not run after callback of getJSON finish, so i get a undefined value in log. Which is right way to make it work? Thank!
Share Improve this question asked Aug 20, 2012 at 16:51 Coder53Coder53 231 gold badge1 silver badge3 bronze badges 1- @TheZ your ment is an answer - you should put it as one so it can get voted up as an answer. – kinakuta Commented Aug 20, 2012 at 16:53
3 Answers
Reset to default 2Return the deffered object from the ajax function and use the always, done or fail methods on it:
function getData(id) {
return $.getJSON('url/to/jsondata',{id: id}, function(data) { //return this
$('#content').data('key', data);
});
}
$(document).ready(function() {
getData('content').always(function() { //is returned as deffered object
console.log($('#content').data('key')); //runs when ajax pleted
});
});
You have already defined the callback in your getJSON
call. To get the results put your console.log code near in the same function as the /** append some data to div#content **/
ment.
Here's the jQuery documentation for getJSON so you can see which is the correct argument and how you can lay it out: http://api.jquery./jQuery.getJSON/
You should put the log-call in the callback-function like this:
function getData(id) {
$.getJSON('url/to/jsondata',{id: id}, function(data) {
/** append some data to div#content **/
$('#content').data('key', 'value');
console.log($('#content').data('key'));
});