Reputation: 7341
I'm having more problem with JSON!
I am using the advice from this article http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Using this I have managed to use Server Side Web Methods to perform actions with AJAX.
In most instances, I just need it to do stuff (save things to a database for example) so don't need to do anything with the response, but now I've come across a situation where I do, and I can't work it out!
The Web Method returns a JSON object, which looks like this:
{"d":"[{\"validDetails\":\"True\",\"lateAlert\":\"\",\"LoginResponse\":\"Logging in Jamie at 16:53 please wait\"}]"}
This is the output shown from Firebug. I am not sure what the \
's are, but bear with it...
The AJAX call and attempt at outputting this response is:
$("form").on("submit", function () {
var LogonObject = new Object;
LogonObject.password = $('#password').val();
var LogonData = JSON.stringify(LogonObject);
$.ajax({
type: "POST",
url: "/logIn.aspx/login_try",
data: LogonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var results = (data.d);
$('#LoginResponse').html(results); // this is a Div to display the result
}
});
});
If I do this, then the #LoginResponse DIV displays:
[{"validDetails":"True","lateAlert":"","LoginResponse":"Logging in Jamie at 16:53 please wait"}]
Which looks to me like a happy JSON Object!
I cannot work out how to get the next level though.
ie, How do I get the result value of validDetails, lateAlert etc?
I have tried:
$.each(results, function (index, element) {
$.each(element, function (index, sub) {
alert(sub);
});
});
And several other variations from info I have found on Google and SO, but it seems to treat the results
variable as a string, not an array, and the output I get on the alerts is each individual character, ie;
[, {, ", v, a, l, i, d, D... etc
So I wondered if results
needed to be converted to JSON again (though I don't know why) so I tried
results = $.parseJSON(data.d)
But that didn't work either.
I'm sure I'm missing something really simple here, but I can't figure out how to do it! :-(
EDIT, the code which generates the response (missing out tons of logic, but this is the important bit):
Public Class OutputObject
Public validDetails, lateAlert, LoginResponse As String 'content of JSON output'
End Class
<System.Web.Services.WebMethod()> _
Public Shared Function login_try(password As String)
Dim outputArray As New ArrayList
Dim Login As New OutputObject()
Login.validDetails = validDetails
Login.lateAlert = lateAlert
Login.LoginResponse = LoginResponse
outputArray.Add(Login)
serializer = New JavaScriptSerializer()
Return serializer.Serialize(outputArray)
end function
Upvotes: 0
Views: 2449
Reputation: 54618
I believe the error is somewhere in your JSON serialization (because you JSON looks like it has be serialized twice). Can we get the code that does that?
Upvotes: 1