0

I have an asp.net page which is returning a list of object as a json string to an ajax request. The string is as follows :

[
    {"Name":"Don","Age":23,"Description":"Tall man with no glasses"}
    ,{"Name":"Charlie","Age":24,"Description":"Short man with glasses"}
]

I want to access each field individually, like the name of the person, his age, his description etc.

How can I do that? I am using JQuery for client-side scripting.

For further clarification, here is the server-side C# code -

protected void Page_Load(object sender, EventArgs e)
{
    if (Request["field1"] != null)
    {            
        createPersonList();
    }
}

private void createPersonList()
{
    List<Person> PersonList = new List<Person>();

    Person Atiq = new Person("Atiq Hasan Mollah", 23, "Whassap Homie");
    Person Sajib = new Person("Sajib Mamud", 24, "Chol kheye ashi");

    PersonList.Add(Atiq);
    PersonList.Add(Sajib);

    string json = JsonConvert.SerializeObject(PersonList);

    Response.Clear();
    Response.Write(json);
    Response.End();
}

The client-side javascript code is as follows -

$(function()
{   
    $("#SimpleButton").click(function()
    {

        $.post("Default.aspx", {field1: $("#field1").val()},function(data)
        {
            data = $.trim(data);
            $("#field2").val(data);

            var myObject = eval('(' + data + ')');

            $(data).each(function(index, person)
            {
                alert(  'Name: ' + person.Name + 
                        ' Age: ' + person.Age + 
                        ' Description: ' + person.Description
                    );
            });
        });
    });
});

Now if I don't use "eval" myself, then how can I pass the arraylist from server-side and then parse it using javascript ?

3
  • I would recommend you to avoid calling the eval method yourself. If you perform your AJAX query with jQuery it will handle the conversion of the server response which represents a JSON encoded object to the object itself. Commented Mar 20, 2010 at 9:59
  • I tried not to use "eval" by myself. Instead I tried to use "$.getJSON" method of the jquery. But when the server returns the JSON encoded string, then if I try to access it, then it is generating some error. I am giving the server side code as well as the whole client-side code for further clarification. Commented Mar 20, 2010 at 10:07
  • If you want to use $.post and still have jQuery parse the JSON automatically, you can tell it via the fourth parameter: $.post("Default.aspx", {field1: $("#field1").val()}, function(data) { ... }, "json");. I will update my answer to reflect this. Commented Mar 20, 2010 at 12:49

2 Answers 2

2

You can ask jQuery to parse the JSON automatically and return a JavaScript object rather than a string:

var people = $.getJSON('http://example.com/path/to/page');

If you want to use POST rather than GET, you can provide a data type as the fourth parameter:

$.post("Default.aspx", {field1: $("#field1").val()}, function(data) { ... }, "json");

You can then access it just as you would a normal object:

$.each(people, function(function (i, person) {
    $('#people').append($('<p>').text(person.Name));
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is the way I usually do it.
1

Assuming you already have the persons array you could use the each method to loop through the elements:

var persons = [
    {"Name":"Don","Age":23,"Description":"Tall man with no glasses"},
    {"Name":"Charlie","Age":24,"Description":"Short man with glasses"}
];

$(persons).each(function(index, person) {
    alert('Name: ' + person.Name + 
          ' Age: ' + person.Age + 
          ' Description: ' + person.Description
    );
});

1 Comment

Well, I just needed the first part, actually, I mean how to convert a string into an actual array, but I managed it by my own. But your answer has taught me a new thing that I didn't know before: accessing a list like that using jquery. Thanks....... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.