0

I have got back response at this line in form of json from web api controller action:

var json = await response.Content.ReadAsStringAsync();

The short version of the response is something like this:

{
    "Response": {
        "ResponseStatus": 1,
        "Error": {
            "ErrorCode": 0,
            "ErrorMessage": ""
        },
        "TraceId": "83b04f8c-f7dd-4755-9767-b0c861ea9e28",
        "Origin": "DEL",
        "Destination": "BOM",
        "Results": [
            [{
                "ResultIndex": "OB12",
                "Source": 6,
                "Fare": {
                    "Currency": "INR",
                    "OtherCharges": 58.29,
                    "ChargeBU": [{
                        "key": "TBOMARKUP",
                        "value": 8.29
                    }, {
                        "key": "CONVENIENCECHARGE",
                        "value": 0
                    }, {
                        "key": "OTHERCHARGE",
                        "value": 50.00
                    }],
                    "Discount": 0,
                },
            }]
        ]
    }
}

The full version is shown at http://pastebin.com/eEE72ySk

Then i am returning back HttpResponse from webApi Controller by sending this json var data to CreateResponse method and returning back res like this:

HttpResponseMessage res = Request.CreateResponse(HttpStatusCode.OK, json);
return res;

I have to return back this res to $.ajax function on view page:

$.ajax(
{
    url: "/api/Flight/SearchFlight",
    type: "Post",
    data: $('form').serialize() + '&' + $.param({ 'TokenId': $("#pageInitCounter").val()}, true),
    success: function (data) {
        alert(data);
        var items = [];
        $.each(data, function (key, val) {
            items.push(key + ' : ' + val + '</br>');
        });    
    }
});

I can see the whole content in alert box. I want to know how to loop through each and every data i got back and assign their values to the respective <div> elements on the view page. The Response which i got back contains several arrays and arrays into arrays. I am confused how to manage each and every data.

2 Answers 2

1

Arrays are accessed with indexers and for an array containing an array, you use

XXX[0][0].YYY

to access the first array within the first array.

The code to access some of your properties would be

$.ajax(
{
    url: "/api/Flight/SearchFlight",
    type: "Post",
    data: $('form').serialize() + '&' + $.param({ 'TokenId': $("#pageInitCounter").val()}, true),
    success: function (data) {
        var responseStatus = data.Response.ResponseStatus; // returns 1
        var errorCode = data.Response.Error.ErrorCode; // returns 0
        var origin = data.Response.Origin; // returns 'DEL'
        var resultIndex = data.Response.Results[0][0].ResultIndex; // returns 'OB12'
    }
});

Most of the data in the arrays seems to contain only one object, or one array containing one object and if that is always the case, then accessing it using [0] or [0][0] will be fine.

For the arrays containing multiple objects such as data.Response.Results[0][0].Fare.ChargeBU, you can use a for loop or $.each() loop, for example

$.each(data.Response.Results[0][0].Fare.ChargeBU, function (index, chargeBU) {
    var key = chargeBU.key // returns "TBOMARKUP", "CONVENIENCECHARGE", "OTHERCHARGE"
});
Sign up to request clarification or add additional context in comments.

14 Comments

I have tried this: $.each(data.Response.Results, function (i, item) { $("#results1").append('<p>' + item.Name + '</p>'); }); Error is: Uncaught TypeError: Cannot read property 'Results' of undefined. same error was for var responseStatus right now i have commented out all the four var.
Its not $.each(data.Response.Results, function (i, item) { its $.each(data.Response.Results[0][0].Fare.ChargeBU, function (index, chargeBU) { - you need to read the answer carefully. And I have tested all this and its works fine. If your still having troubles, I'll create a fiddle to prove it.
Then the data you have shown in that image is not what your really getting. I'll create a fiddle for you a bit later (give me 30-40 min)
Sir,In Results its giving me back 25 arrays, i am showing u two in this link:pastebin.com/YNthgivV as u said i tried THIS:var responseStatus = data.Response.ResponseStatus; $('#divResult1').append(responseStatus); but its giving me error Uncaught TypeError: Cannot read property 'ResponseStatus' of undefined
And another updated fiddle to show the each loop.
|
0

Try This

{
    url: "/api/Flight/SearchFlight",
    type: "Post",
    data: $('form').serialize() + '&' + $.param({ 'TokenId': $("#pageInitCounter").val()}, true),
    success: function (data) {
        alert(data);
        var items = [];
        $.each(data.Response.Results, function (key, val) {
            items.push(key + ' : ' + val + '</br>');
        });
    }
}; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.