简体   繁体   English

如何使用jQuery从JSON格式读取数据

[英]How to read data from json format using jquery

在此处输入图片说明

How to read data from json format using jquery. 如何使用jquery从json格式读取数据。 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. 编辑:Web api将返回数据作为列表对象。

[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); 使用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.stringify将Javascript对象转换为JSON文本,并将该JSON文本存储在字符串中。

JSON.parse turns a string of JSON text into a Javascript object. JSON.parse将JSON文本字符串转换为Javascript对象。

How to access JSON object 如何访问JSON对象

FYI, as of jQuery 3.0, $.parseJSON is deprecated. 仅供参考,自jQuery 3.0起,不推荐使用$ .parseJSON。 To parse JSON objects, use the native JSON.parse method instead. 要解析JSON对象,请改用本机JSON.parse方法。

 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. 如果获取[object,object],则意味着您已经获取了Json Object。 And if you need some clarifications, please share the expected Json you want.Thanks 如果您需要一些说明,请分享您想要的期望Json。

Use JSON.stringify(object) . 使用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. 假设服务器端脚本未设置正确的Content-Type: application/json响应标头,则需要使用dataType: 'json'参数向jQuery指示这是JSON。

You should not use data variable in $.each() . 您不应在$.each()使用data变量。 Then you could use the $.each() function to loop through the data: 然后,您可以使用$.each()函数遍历数据:

$.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方法:例如:

$.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. 注意:从jQuery 3.0开始,不推荐使用$.parseJSON To parse JSON objects, use the native JSON.parse method instead. 要解析JSON对象,请改用本机JSON.parse方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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