Reputation: 2170
I have a JSON response that is formatted from my C# WebMethod using the JavascriptSerializer Class. I currently get the following JSON back from my query:
{"d":"[{\"Lat\":\"51.85036\",\"Long\":\"-8.48901\"},{\"Lat\":\"51.89857\",\"Long\":\"-8.47229\"}]"}
I'm having an issue with my code below that I'm hoping someone might be able to shed some light on. I can't seem to get at the information out of the values returned to me. Ideally I would like to be able to read in the Lat and Long values for each row returned to me.
Below is what I currently have:
$.ajax({
type: "POST",
url: "page.aspx/LoadWayPoints",
data: "{'args': '" + $('numJourneys').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d != '[]') {
var lat = "";
var long = "";
$.each(msg.d, function () {
lat = this['Lat'];
long = this['Long'];
});
alert('lat =' + lat + ', long =' + long);
}
}
});
I think the issue is something to do with how the JSON is formatted but I might be incorrect. Any help would be great.
Thanks, Rich
Upvotes: 0
Views: 2049
Reputation: 42928
What's happening is you're getting JSON encoded inside a string within your JSON. It's redundant, but there is a solution without changing your output method.
To handle this, jQuery has a JSON parser ($.parseJSON()
) you can use do parse the string inside the response.
So I believe you would do it like this:
$.ajax({
type: "POST",
url: "page.aspx/LoadWayPoints",
data: "{'args': '" + $('numJourneys').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d != '[]') {
var content = $.parseJSON(msg.d);
var lat = "";
var long = "";
$.each(content, function() {
lat = this['Lat'];
long = this['Long'];
});
alert('lat =' + lat + ', long =' + long);
}
}
});
Upvotes: 2
Reputation: 3310
I think you need something like that:
$.ajax({
type: "POST",
url: "page.aspx/LoadWayPoints",
data: "{'args': '" + $('numJourneys').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$.each(msg.d, function () {
var lat = "";
var long = "";
lat = this.Lat; // Lat/Long this is how you called it in your JSON responce
long = this.Long;
alert('lat =' + lat + ', long =' + long);
});
}
});
hope it helps
Upvotes: 0
Reputation: 3618
Please try this:
$.each(msg.d, function () {
lat = this['Lat'];
long = this['Long'];
});
After going through the JSON there is no MapLatPosition or MapLongPosition
HTH
Upvotes: 0
Reputation: 6375
Looks like your JSON is incorrectly built:
{"d":"[{\"Lat\":\"51.85036\",\"Long\":\"-8.48901\"},{\"Lat\":\"51.89857\",\"Long\":\"-8.47229\"}]"}
Probably should be:
{"d":[{"Lat":"51.85036","Long":"-8.48901"},{"Lat":"51.89857","Long":"-8.47229"}]}
Notice the {"d":"..."}
? looks like your "d" points to a string, not an array.
Upvotes: 1