Reputation: 75
Ahoy!
I am using a WCF service to handle ajax calls from a web server on a seperate domain (therefore employing JSONP). My call looks like this:
$.ajax({
dataType: 'jsonp',
type: 'GET',
url: 'http://localhost/s.svc/login?callback=?&l=en&e=foo&p=bar',
success: function (serverData) {
// [...]
},
error: function (jqXHR, textStatus, errorThrown) {
// [...]
}
});
The response I get from the server looks like this:
?({"DataIsValid":true,"ErrorOccurred":false,"EmailAddressValidationMessage":"","PasswordValidationMessage":""});
And jQuery subsequently throws a parsererror when reading it.
The response above looks like valid JSON and, per the documentation, I think "?callback=?" is appropriate for $.ajax calls using JSONP.
Thanks in advance for pointing out what I am obviously missing :-)
Upvotes: 1
Views: 11804
Reputation: 1
I was missing below in MVC action method response(wrapping the reponse in callback method).
response.Write(request.Params["callback"] +"(" +htmlContent +");");
And jquery ajax call should be like below.
jQuery.ajax({
url:"https://servername/virtualDirectory/ActionMethod,
crossDomain: true,
dataType: 'jsonp',
type: 'GET',
cache: false,
jsonp:"callback",
success: function (data) {
alert('success');
$fs("#fs_container").htm(data);
},
error: function (data, status, req) {
alert(req.responseText + " " + status);
}
});
Upvotes: 0
Reputation: 341
A couple things i see here:
serverData
will be a string. Parse it with jQuery.parseJSON()
or JSON.parse()
:var data = jQuery.parseJSON(serverData); // or use JSON.parse(serverData);
That should do it.
One final thing. If you start getting "Unexpected token..." errors on the parse you probably have a control character hidden somewhere in your JSON string. I had this issue and it was a newline ("\n"). Figure out which character it is by getting the string to parse in something like Chrome's dev tools console, and then replace it:
var data = jQuery.parseJSON(serverData.replace(/\n/g,""));
Upvotes: 3