简体   繁体   中英

How to read data from JSON

I can receive the response in JSON, but I am not able to read it. Here is my code:

$(document).ready(function () {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/BindDatatable",
        data: "{}",
        dataType: "json",
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                alert(data.d[i].name);
            }
        },
        error: function (result) {
            alert("Error");
        }
    });
});

Instead of $.ajax, try using $.getJSON, or use JSON.parse(data) when data comes, The actual problem is with JSON data, you need to convert it into JavaScript object to use it. Once it parse and converts into JavaScript Object, you can Access like data.d[i].name

As far as i understand in your case you are getting JSON Object in variable data in method success then and you json format is this

"d":[{"__type":"_Default+UserDetails","id":1,"name":"mks","email":"aa@gmail.com",‌​"age":22}]

then you just have to change the following condition

success: function (data) {
        for (var i = 0; i < data.d.length; i++) {
            alert(data.d[i].name);
        }
    },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM