先來一段簡單的javascript對象的遍歷:var json = [ {"id":"1","tagName":"apple"}, {"id":"2","tagName":"orange"}, {"id":"3","tagName":"banana"}, {"id":"4",...
先來一段簡單的javascript對象的遍歷:
var json = [ {"id":"1","tagName":"apple"}, {"id":"2","tagName":"orange"}, {"id":"3","tagName":"banana"}, {"id":"4","tagName":"watermelon"}, {"id":"5","tagName":"pineapple"} ]; $.each(json, function(idx, obj) { alert(obj.tagName); });
當為JSON字元串時:
var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"}, {"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"}, {"id":"5","tagName":"pineapple"}]'; $.each(json, function(idx, obj) { alert(obj.tagName); });
在Chrome中,他會顯示 錯誤:
Uncaught TypeError: Cannot use 'in' operator to search for '156' in [{"id":"1","tagName":"apple"}...
解決方案:
var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"}, {"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"}, {"id":"5","tagName":"pineapple"}]'; $.each(JSON.parse(json), function(idx, obj) { alert(obj.tagName); }); //or $.each($.parseJSON(json), function(idx, obj) { alert(obj.tagName); });