jquery loop on Json data using $.each

前端 未结 4 1953
后悔当初
后悔当初 2020-11-22 14:56

I have the following JSON returned in a variable called data.

THIS IS THE JSON THAT GETS RETURNED...

[ 
{\"Id\": 10004, \"PageName\"         


        
相关标签:
4条回答
  • 2020-11-22 15:35
    $.each(JSON.parse(result), function(i, item) {
        alert(item.number);
    });
    
    0 讨论(0)
  • 2020-11-22 15:40
    var data = [ 
     {"Id": 10004, "PageName": "club"}, 
     {"Id": 10040, "PageName": "qaz"}, 
     {"Id": 10059, "PageName": "jjjjjjj"}
    ];
    
    $.each(data, function(i, item) {
        alert(data[i].PageName);
    });
    
    $.each(data, function(i, item) {
        alert(item.PageName);
    });
    

    these two options work well, unless you have something like:

    var data.result = [ 
     {"Id": 10004, "PageName": "club"}, 
     {"Id": 10040, "PageName": "qaz"}, 
     {"Id": 10059, "PageName": "jjjjjjj"}
    ];
    
    $.each(data.result, function(i, item) {
        alert(data.result[i].PageName);
    });
    

    EDIT:

    try with this and describes what the result

    $.get('/Cms/GetPages/123', function(data) {
      alert(data);
    });
    

    FOR EDIT 3:

    this corrects the problem, but not the idea to use "eval", you should see how are the response in '/Cms/GetPages/123'.

    $.get('/Cms/GetPages/123', function(data) {
      $.each(eval(data.replace(/[\r\n]/, "")), function(i, item) {
       alert(item.PageName);
      });
    });
    
    0 讨论(0)
  • 2020-11-22 15:42

    Have you converted your data from string to JavaScript object?

    You can do it with data = eval('(' + string_data + ')'); or, which is safer, data = JSON.parse(string_data); but later will only works in FF 3.5 or if you include json2.js

    jQuery since 1.4.1 also have function for that, $.parseJSON().

    But actually, $.getJSON() should give you already parsed json object, so you should just check everything thoroughly, there is little mistake buried somewhere, like you might have forgotten to quote something in json, or one of the brackets is missing.

    0 讨论(0)
  • 2020-11-22 15:45

    getJSON will evaluate the data to JSON for you, as long as the correct content-type is used. Make sure that the server is returning the data as application/json.

    0 讨论(0)
提交回复
热议问题