Reputation: 6190
I am developing HTML5, jQuery mobile application. I have to use 3rd party JSON web service to obtain data. However I am having parseerror in my jquery function. It seems the issue is that web service send JSON. I have to use JSONP since it is cross-domain. Is there anyway to do this using jQuery or javascript. Here is the code I am using.
$.ajax({
url : jsonServiceURL + "scheduleService/retrieveMySchedules.json?callback=?",
dataType : "json",
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
timeout : 5000
}).success(function() {
alert('pass');
}).error(function(httpObj, textStatus) {
alert(textStatus);
});
The request goes. The response also comes. But it says parseerror. I feel this has something difference in JSON and JSONP. If I set URL to something like http://www.geonames.org/postalCodeLookupJSON?postalcode=10504&country=US&callback=? my code works fine there is no issue. The 3rd party web service also correct since all the iphone apps works fine. Only difference I see is JSON start with [{
and JSONP start with somefunction({
.
The JSON is valid. I checked it with some online tools and also there are couple of iphone apps working with that web service without an issue. It seems I can't parse it with jquery since they send JSON instead of JSONP. Please correct me if my thought is wrong. What are the possible solutions for this?
Upvotes: 1
Views: 1788
Reputation: 382170
If you're doing cross-domain requests, use jsonp. That's good. It's just a little different from your standard json request (done with XmlHttpRequest).
You must send your request precising it's jsonp :
$.ajax({
url : jsonpServiceURL + "scheduleService/retrieveMySchedulesJsonp?callback=?",
dataType : "jsonp"
});
And then you must have a function in your code that will be your callback :
function InBrowser_receive(answer) {
console.log('received:', answer)
// do things with answer (the received json)
}
Personally, I usually don't bother with sending the name of the callback to the server, as I write the server part too : I simply hardcode the callback name serverwise.
And I like to send arguments to the server using json structures too. So my function sending the request is usually like this :
function sendToServer(message) {
$.ajax(
{
url: serverUrl,
data: 'theQuery=' + JSON.stringify(message),
crossDomain: true,
dataType: 'jsonp'
}
);
}
Here's an example in one of my open source codes : https://github.com/Canop/braldop/blob/master/chrome/braldop/inext_com.js
The sending function is
braldop.sendToBraldopServer
and the receiving one is
receiveFromMapServer
Upvotes: 1