简体   繁体   中英

How to read data from json format using jquery

在此处输入图片说明

How to read data from json format using jquery. below is what i have tried, but unfortualtly i couldn't able to read exact data which i want.

 $.ajax({
            url: '@Url.HttpRouteUrl("GetDistrictList", new { })',
            type: 'GET',
            datatype: "json",
            success: function (data, txtStatus, xhr) {
                console.log(data);
                if (data != null) {

                    $.each(data, function (i, item) {
                        alert(data[0]);
                        alert(data[0].DistrictCode)
                        alert(item);
                        alert(item[0]);
                        alert(item.DistrictCode);
                        $('#tblDistricts > tbody').append('<tr><td>'+item.DistrictCode+'</td><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>');

                    })
                }
            },
            error: function (xhr, textStatus, errorThrown) { 
                console.log("error in GetDistrictList : " + errorThrown);
            }
        });'

In alert box , I'm getting 'undefined' or '[object] [Object] only, I could not able to read exact data. I got stuck here.

Edit: Web api will return the data as List objects.

[HttpGet]
        [Route("GetDistrict/", Name = "GetDistrictList")]
        public List<DistrictModels> GetDistrictList()
        {

            BAL_District oBAL_District = new BAL_District();

            return oBAL_District.GetDistrictList();

        }

Use var Data = $.parseJSON(response);

Example

var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );

JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string.

JSON.parse turns a string of JSON text into a Javascript object.

How to access JSON object

FYI, as of jQuery 3.0, $.parseJSON is deprecated. To parse JSON objects, use the native JSON.parse method instead.

 var json = [ { 'red': '#f00' }, { 'green': '#0f0' }, { 'blue': '#00f' } ]; $.each(json, function () { $.each(this, function (name, value) { console.log(name + '=' + value); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

我认为您希望调用此函数-http://api.jquery.com/jquery.parsejson/

if you are getting [object,object] it means you have already fetched the Json Object. And if you need some clarifications, please share the expected Json you want.Thanks

Use JSON.stringify(object) . It is super safe way to print out.

   $.ajax({
        url: '@Url.HttpRouteUrl("GetDistrictList", new { })',
        type: 'GET',
        datatype: "json",
        success: function (data, txtStatus, xhr) {
            console.log(data);
            if (!!data) {
                // '!data' means data variable is not available and '!!data' returns true:boolean if variable is valid

                //idx is 'index', I made the code as a loop. It will not work if array is empty. 
                //It is good way to avoid error
                for(var idx in data){
                    if(idx == 0) {
                        //JSON.stringify makes object type to string type. It is safe to use since it is a native javascript function
                        alert(JSON.stringify(data[idx]);
                        //You can access member by 'data[idx].memberName'
                        //DOM adding code can be here
                    }
                }
            }
        },
        error: function (xhr, textStatus, errorThrown) { 
            console.log("error in GetDistrictList : " + errorThrown);
        }
    });

Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json' parameter.

You should not use data variable in $.each() . Then you could use the $.each() function to loop through the data:

$.ajax({
    url: '@Url.HttpRouteUrl("GetDistrictList", new { })',
    type: 'GET',
    datatype: "json",
    success: function (data, txtStatus, xhr) {
        console.log(data);
        if (data != null) {

            $.each(data, function (index, element) {
                alert(element);
                alert(element[0]);
                alert(element.DistrictCode);
                $('#tblDistricts > tbody').append('<tr><td>'+element.DistrictCode+'</td><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>');
            });
        }
    },
    error: function (xhr, textStatus, errorThrown) { 
        console.log("error in GetDistrictList : " + errorThrown);
    }
});'

or use the $.getJSON method: For example:

$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('<div>', {
            text: element.name
        }));
    });
});

Note: As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON objects, use the native JSON.parse method instead.

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