2011-05-10 14 views
7

Eventuali duplicati:
How do I return JSON and loop through the returned json in jQuery in MVC app?Come posso eseguire il loop dei dati JSON restituiti da jQuery?

Questo è il mio dati restituiti dal Controller MVC e ottengo questo nel mio successo di callback:

[{ "_id" : { "$oid" : "4dc8" }, "eid" : { "$oid" : "4da" }, "user" : "bob", "text" : "First comment!!", "dt" : { "$date" : 1304966277978 } }, 
{ "_id" : { "$oid" : "4dc8" }, "eid" : { "$oid" : "4da" }, "user" : "bob", "text" : "Second comment!!", "dt" : { "$date" : 1304966347677 } }, 
{ "_id" : { "$oid" : "4dc8" }, "eid" : { "$oid" : "4da" }, "user" : "bob", "text" : "Third comment!!", "dt" : { "$date" : 1304966493240 } } 
] 

Controller:

[HttpGet] 
public JsonResult GetComments(params...) 
{ 
    return Json(new { comments = GetFromDB().ToJson() }, JsonRequestBehavior.AllowGet); 
} 

Problema: Ho provato diversi modi per eseguire il loop delle righe. Ma tutto sembra un ciclo infinito.

$.ajax(
     { 
      type: "GET", 
      url: "/comment/GetComments", 
      dataType: "json", 
      data: "app=" + app + "&eid=" + eid + "&pg=" + pg + "&pgs=" + pgs, 
      success: function (result) { 
       $.each(result[comments], function() { 
        $.each(this, function (k, v) { 
         alert('this a column or attribute'); 
        }); 
        alert('end of row'); 
       }); 
      }, 
      error: function (req, status, error) { 
       alert('Error=' + error + ' & Status=' + status); 
      } 
     }); 

cercato anche:

$.each(result["comments"], function (key, value) { 
    alert('comment found'); 
}); 

come posso ciclo le righe & di accesso il valore di ogni attributo?

+0

ciò che fa la tua ajax chiamata assomigliare? –

+0

per favore modifica il tuo post piuttosto che incollare il codice in commment – mcgrailm

+0

hai postato praticamente la stessa cosa oggi a: http://stackoverflow.com/questions/5953761/how-do-i-return-json-and-loop-through-the -returned-json-in-jquery-in-mvc-app/5954010 # 5954010 –

risposta

4

Si potrebbe utilizzare un semplice for ciclo:

for (var i = 0, len = results.length; i < len; i++) { 
    // do something with results[i].text 
} 

See example →


EDIT: Se avete bisogno di convertire prima una stringa JSON in un oggetto JavaScript quindi prima del ciclo è necessario:

results = JSON.parse(results); 
+0

Funziona nel jsfiddle ma non nel mio browser. alert ('len =' + results.length) mi stampa i caratteri totali nella risposta json non il numero di elementi nella risposta. È questa la ragione? Sta trattando JSON come testo normale ?? – kheya

+0

JSON è un formato di testo: http://www.json.org/ – Tamler

+0

Ho aggiornato la mia risposta. – mVChr

1
$.getJSON("YourControllerHere.XXX",{}, function(data){ 
    $.each(data, function(key, val) { 
     $('#someLocation').append('<li>' + val.text + '</li>'); //This is just an example. You can do something with each row/ value pair here. 
    }); 
}); 

Dovresti essere in grado di scorrere le righe e i valori con questo.

migliore,

T

1

Il tuo primo problema è che non v'è alcun result["comments"] campo nel JSON. Stai recuperando un array, di quello che presumo siano i commenti stessi. Quindi è necessario iterare su questo. Qualcosa come

$.each(result, function(k, v) { console.log(v.user); }); 

dovrebbe funzionare, l'ho appena provato nel browser. I codice seguente esegue un'iterazione le righe, e poi scorre gli attributi di ogni riga:

$.each(foo, function(k, row) { $.each(row, function(attr, value) { console.log(attr, value); }) }); 
1
for(var key in json) 
    for(var key in (obj = json[key])) 
     { 
      //obj holds the current object in the json array 
      console.log(obj[key]); 
     }  
Problemi correlati