Returns value using jQuery each () function

I am new to javascript and I would like to get the values ​​from JSON and insert it into an array so that I can parse this array again in another function. But I do not know how to return an array after clicking inside it.

In the following script, I cannot display values ​​in elements

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 can I access the array?

thanks!

+6
source share
2 answers

Just enter 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]); }); } 
+3
source

You are not returning from an AJAX call, you are calling a callback function when this is 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 will be called when an AJAX call is made. This cannot return the value of another function, so all your logic should be inside this callback function.

UPDATE: you can also pass the callback function to gC when it is 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 as follows:

 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 added to the question. This must 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]); } }) 
+4
source

Source: https://habr.com/ru/post/894282/


All Articles