Let's start with a simple JavaScript object traversal:
var json = [ {"id": "1", "TagName": "Apple"}, {"id": "2", "TagName": "Orange"}, {"id": "3", "TagName": "Banana"}, {"id": "4", "TagName": "Watermelon"}, {"id": "5", "TagName": "Pineapple" function(idx, obj) { alert (obj.tagname);});
< Span class= "token string" >< Span class= "token punctuation" >< Span class= "token punctuation" >
When a JSON string:
var json = '[{' id ': ' 1 ', ' tagName ': ' Apple '},{' id ': ' 2 ', ' tagName ': ' Orange '},{' id ': ' 3 ', ' tagName ': ' Banana ' },{"id": "4", "TagName": "Watermelon"},{"id": "5", "TagName": "Pineapple"}]'; function (idx, obj) { alert (obj.tagname);});
< Span class= "token string" >< Span class= "token punctuation" >< Span class= "token punctuation" >
In Chrome, he will display an error:
for inch [{"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"}]'; function (idx, obj) { alert (obj.tagname);}); // function (idx, obj) { alert (obj.tagname);});
< Span class= "token punctuation" >
< Span class= "token punctuation" >< Span class= "token punctuation" >< Span class= "token function" >< Span class= "token punctuation" >
JQuery loop over JSON string –$.each instance