Javascript - Using a variable to get a piece of an array -


i working on webpage connects cgi backend. cgi backend far works perfectly, don't know javascript well, struggling handle getting results ajax json requests.

what have:

a javascript function queries cgi.

the cgi responds in json array.

    {     "array": [         {             "line": "1",             "numbers": "12321",             "var": "12321",             "var2": "12321"         },         {             "line": "2",             "numbers": "-1",             "var": "12320",             "var2": "6160"         }     ] } 

line, numbers, var, , var2 must placed in separate cells of table.

<table> <tr> <th>line</th><th>numbers</th><th>var</th><th>var2</th> </tr> <tr> <td>array[0].line</td><td>array[0].numbers</td><td>array[0].var</td><td>array[0].var2</td> </tr> <tr> <td>array[1].line</td><td>array[1].numbers</td><td>array[1].var</td><td>array[1].var2</td> </tr> </table> 

so, here problem:

i never know how many objects going inside array. here there 2, there 20. can modify json if needed. how make loop until hits last object?

there several different ways. traditional 1 use simple loop:

for (var = 0, len = array.length; < len; i++) {     //build table row using array[i].line, etc } 

a while got array.foreach, long don't have support old versions of ie work fine (you can polyfill them):

array.foreach (function (idx, elt) {     //build table row using elt.line, etc }); 

if you're using jquery, there's $.each:

$.each(array, function (idx, elt) {     //build table row using elt.line, etc }); 

here's more complete example of need, using jquery library (not essential, makes things easier):

var url = '/cgi-bin/your_script_name.cgi'; var html = '<table><tr><th>line</th><th>numbers</th><th>var</th><th>var2</th></tr>'; $.get(url, function (response) {     $.each(response.array, function (idx, elt) {         html += '<tr><td>' + elt.line + '</td><td>' + elt.numbers + '</td><td>' + elt.var + '</td><td>' + elt.var2 + '</td></tr>';     });     html += '</table>';     $('#target-element').html(html); }); 

in example you're putting table element id target-element, , cgi script located @ /cgi-bin/your_script_name.cgi. if can't use jquery, you'll need manually make xmlhttprequest, set responsetype 'json', , bind function onload (or if supporting old browsers, onreadystatechange , check readystate === 4). hope helps.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -