tags:

views:

315

answers:

3

Hello, my jQuery.ajax return JSon object. I firstly read other articles. but their response text not likes mine. My Response content: from firebug response

{"item":"[{\"country\":\"USA\",\"lan\":\"EN\"},{\"country\":\"Turkiye\",\"lan\":\"TR\"}]"}

Now i trying to alert countryName:

$('#loadData').click(function() {
            $.ajax({
                type: "POST",
                url: "WS/myWS.asmx/getDaa",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                $("#jsonResponse").html(msg);
                    $.each(msg.item, function(i, d) {
                        alert(this.country);
                        debugger;
                    });
                },
            });
        });

but it is alerting "undefined"

+6  A: 
{"item":"[{\"country\":\"USA\",\"lan\":\"EN\"},{\"country\":\"Turkiye\",\"lan\":\"TR\"}]"}
        ^
        |
        +---- It's a string, not an array !

Your JSON should look like

{"item":[ {"country":"USA","lan":"EN"},{"country":"Turkiye","lan":"TR"}]}

Then you can access it like

country = msg.item[0];
lang    = country.lan;

for (i=0; i< item.length; i++) { alert ( item[i].country); }

etc...

David V.
thanks, for understanding Json structure
loviji
+2  A: 

The reason is that msg.item is a string.

The reason that it is a string is that initial double quote you have after item:. This also explains why your double quotes are escaped. You have:

{"item":"[{\"country\":\"USA\",\"lan\":\"EN\"},{\"country\":\"Turkiye\",\"lan\":\"TR\"}]"}

When you should have:

{"item":[{"country":"USA","lan":"EN"},{"country":"Turkiye","lan":"TR"}]"}
Dancrumb
thanks, for understanding Json structure
loviji
+7  A: 

The value of item is a string. Thus you first need to parse it as json. Try this.

$("#jsonResponse").html(msg);
    var item = jQuery.parseJSON(msg.item)
    $.each(item, function(i, d) {
        alert(this.country);
        debugger;
    });
},
jitter
thanks, with parseJson you solve all my need:)
loviji
Note that your jquery call expects a JSON response (dataType: "json"), jquery parses it for you. The correct solution is *not* to parse it again using parseJSON (even if it works in this case), but to output the correct JSON in your script "WS/myWS.asmx/getDaa"
David V.
@David-V: ok. I am analyzing this problem. i used JSonSerializer() method in C# and get result like this.
loviji