开发者

Return a value with jQuery each() function

i'm new to javascript, and I would like to retrieve values from JSON and push it into an array so that I can parse again this array in another function, But I don't know how to return the array after pushing element inside it.

In the following script I can't display values in 开发者_如何学Goitems

function gC(b,c,p) {

    $.getJSON('getmonths', 'b='+b+'&c='+c+'&p='+p, processJSON);    
}

function processJSON(data) {
      var retval = [];
      $.each(data, function(key, val) {

          retval.push(val); 
          //alert(retval.pop());
      });
      return retval;
}

    $(document).ready(function(){
       var b = $("#b").val();
       var c = $("#c").val();
       var p = $("#p").val();

       var items = [];

       items = gC(b,c,p);
       var i = 0;

       $('td').each(function(index) {
          $(this).attr('bgcolor', items[i]);
          i++;
       }

How could I access the array ?

thank !


You don't return from an AJAX call, you have it call a callback function when it's done.

function gC(b,c,p) {
    var retval = [];
    $.getJSON('getmonths', 'b='+b+'&c='+c+'&p='+p, processData);
}

function processData(data){
  var retval = [];
  $.each(data, function(key, val) {
      retval.push(val); 
      //alert(retval.pop());
  });
  alert(retval);
}

processData would be called when the AJAX call is done. This can't return a value to another function, so all your logic has to be inside this callback function.

UPDATE: You can also pass in a callback function to gC to be called when it's done.

function gC(b,c,p,f) {
    var retval = [];
    $.getJSON('getmonths', 'b='+b+'&c='+c+'&p='+p, function(d){
       if(typeof f == 'function'){
         f(d);
       }
    });
}

Then you call gC like so:

gC(b,c,p,function(data){
    var retval = [];
    $.each(data, function(key, val) {
        retval.push(val); 
        //alert(retval.pop());
    });
    alert(retval);
});

UPDATE2: I saw the code you added to the question. This needs to be done in the callback.

gC(b,c,p,function(data){
    var items = [];
    $.each(data, function(key, val) {
       items.push(val);
    });
    $('td').each(function(index){  // You don't need a separate i variable
                                   // you can just use the index from the loop
      $(this).attr('bgcolor', items[index]);
   }
})


Just have the code inside the callback:

function processJSON(data) {
    var retval = [];
    $.each(data, function(key, val) {
        retval.push(val); 
    });
    $('td').each(function(index) {
        if (index < retval.length)
            $(this).attr('bgcolor', retval[index]);
    });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜