jQuery bucle sobre JSON resultado de AJAX Éxito?


En la devolución de llamada jQuery AJAX success quiero hacer un bucle sobre los resultados del objeto. Este es un ejemplo de cómo se ve la respuesta en Firebug.

[
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]

¿Cómo puedo hacer un bucle sobre los resultados para tener acceso a cada uno de los elementos? He intentado algo como a continuación, pero esto no parece estar funcionando.

jQuery.each(data, function(index, itemData) {
  // itemData.TEST1
  // itemData.TEST2
  // itemData.TEST3
});
Author: Tomalak, 2009-04-09

10 answers

Puede quitar el bucle exterior y reemplazar this con data.data:

$.each(data.data, function(k, v) {
    /// do stuff
});

Estabas cerca:

$.each(data, function() {
  $.each(this, function(k, v) {
    /// do stuff
  });
});

Tiene una matriz de objetos/mapas para que el bucle externo itere sobre ellos. El bucle interno itera sobre las propiedades de cada elemento objeto.

 225
Author: cletus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-05 12:57:09

También puedes usar la función getJSON :

    $.getJSON('/your/script.php', function(data) {
        $.each(data, function(index) {
            alert(data[index].TEST1);
            alert(data[index].TEST2);
        });
    });

Esto es realmente solo una nueva redacción de la respuesta de ifesdjeen, pero pensé que podría ser útil para la gente.

 77
Author: clone45,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-01 20:36:13

Si usas Fire Fox, simplemente abre una consola (usa la tecla F12) y prueba esto:

var a = [
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
];

$.each (a, function (bb) {
    console.log (bb);
    console.log (a[bb]);
    console.log (a[bb].TEST1);
});

Espero que ayude

 38
Author: 0100110010101,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-18 09:41:49

Para cualquier otra persona atascada con esto, probablemente no esté funcionando porque la llamada ajax está interpretando los datos devueltos como texto, es decir, aún no es un objeto JSON.

Puede convertirlo en un objeto JSON manualmente usando el comando parseJSON o simplemente agregando la propiedad DataType: 'json' a su llamada ajax. por ejemplo,

jQuery.ajax({
    type: 'POST',
    url: '<?php echo admin_url('admin-ajax.php'); ?>',
    data: data, 
    dataType: 'json', // ** ensure you add this line **
    success: function(data) {
        jQuery.each(data, function(index, item) {
            //now you can access properties using dot notation
        });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("some error");
    }
});
 14
Author: Dave Hilditch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-10 21:33:09

Acceda a la matriz json como lo haría con cualquier otra matriz.

for(var i =0;i < itemData.length-1;i++)
{
  var item = itemData[i];
  alert(item.Test1 + item.Test2 + item.Test3);
}
 12
Author: Toby Allen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-30 08:58:48

Intenta jQuery.función map, funciona bastante bien con mapas.

var mapArray = {
  "lastName": "Last Name cannot be null!",
  "email": "Email cannot be null!",
  "firstName": "First Name cannot be null!"
};

$.map(mapArray, function(val, key) {
  alert("Value is :" + val);
  alert("key is :" + key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 4
Author: PanwarS87,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-30 15:36:06

También puede usar la función getJSON:

$.getJSON('/your/script.php', function(data) {
    $.each(data, function(index) {
        alert(data[index].TEST1);
        alert(data[index].TEST2);
    });
});
 4
Author: Anurag Yadav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-26 06:29:29

Esto es lo que se me ocurrió para ver fácilmente todos los valores de datos:

var dataItems = "";
$.each(data, function (index, itemData) {
    dataItems += index + ": " + itemData + "\n";
});
console.log(dataItems);
 3
Author: Yovav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-02 04:18:33

$each funcionará.. Otra opción es jQuery Ajax Callback for array result

function displayResultForLog(result) 
{
       if (result.hasOwnProperty("d")) {
           result = result.d
       }

    if (result !== undefined && result != null )
    {
        if (result.hasOwnProperty('length')) 
        {
            if (result.length >= 1) 
            {
                for (i = 0; i < result.length; i++) {

                    var sentDate = result[i];

                }
            }
            else 
            {
                $(requiredTable).append('Length is 0');
            }
        }

        else 
        {
            $(requiredTable).append('Length is not available.');
        }

    }
    else 
    {
        $(requiredTable).append('Result is null.');
    }
  }
 0
Author: Lijo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:25

Si no desea alert, es decir, desea html, haga esto

...
    $.each(data, function(index) {
        $("#pr_result").append(data[index].dbcolumn);
    });
...

NOTA: use "append" no "html" de lo contrario, el último resultado es lo que verá en su vista html

Entonces su código html debería tener este aspecto

...
<div id="pr_result"></div>
...

También puede aplicar estilo (agregar clase) al div en jquery antes de que se muestre como html

 0
Author: Adepoju-Conde Adesegun Chris.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-13 15:09:16