简体   繁体   中英

Unable to parse JSON returned by JQuery ajax call

I am calling a method using JQuery ajax given below

$.post('../User/GetCountry',
        {
            zone: 1
        },
        function (data) {
            alert(data);
            alert(data["Countries"]);
        }, "json").fail(function (jqXHR, textStatus, errorThrown) {
            //alert(textStatus);
        });

C# code

public static string GetCountry()
    {
        var result = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Countries.GetAll());
        return result;
    }

Now when I debug my code on server side i see the below result which is perfect json according to me

[{"Id":4,"Name":"France"},{"Id":3,"Name":"Germany"}]

But in javascript I am getting the json as

[[object Object],[object Object]]

Can anyone please let me know what I am missing here

SOLVED USING var jsonData = JSON.stringify(data); var jsonParse = JSON.parse(jsonData);

There's a few issues with your code. First, despite the fact that you're passing a parameter zone to the web service method the method itself doesn't receive this parameter. Second, if you want to return JSON don't use the return type string. Use JSONResult . This will allow you to remove the static keyword as well. I'd recommend changing your method like so:

public JSONResult GetCountry(int? zone)
{
    // ...
}

There are two final changes you should make. The first is to use ASP.Net MVC's built in Json() method to handle serialization of your object. The second is that you should always project your data layer results even if they happen to already be in the structure you want to use. This way if you change your data layer object in a way that breaks the service you'll get a compile error instead of a run time exception.

return Json(from c in Countries.GetAll() select new { Id = c.Id, Name = c.Name })

I'd also recommend avoiding using $.get or $.post as they abstract away settings that can be useful when access web services. If you want to shorthand it I'd recommend wrapping the $.ajax call in your own function. You're also going to want to think about standardizing your web service responses. Your web service is a protocol of sorts and as such it benefits from having a well defined header. For a more in-depth explanation take a look here: Introduction to MVC Service Based Web Applications

尝试这个 :

alert(data[0].Name)
$.ajax({
    type: 'POST',
    url: '../User/GetCountry',
    data: {
        zone: 1
    },
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

works good for me. You need to make sure you're sending a content-type of "application/json", preferably using the Json() helper method in Controller .

Solved this after searching bit more

$.post('../User/GetCountry',
    {
        zone: 1
    },
    function (data) {
        var jsonData = JSON.stringify(data); 
        var jsonParse = JSON.parse(jsonData);
        }, "json").fail(function (jqXHR, textStatus, errorThrown) {
          alert(textStatus);
    });

Try using JSON.parse():

$.post('../User/GetCountry',
        {
            zone: 1
        },
        function (data) {
            data=JSON.parse(data)

            alert(data["Countries"][0].Name);
        }, "json").fail(function (jqXHR, textStatus, errorThrown) {
            //alert(textStatus);
        });

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