I have a simple html file. It access url1 and successfully parse the json response.
CLIENT -> URL1 -> Response to client
I modified my code in html and invoked URL2
CLIENT -> URL2 -> URL1 -> Response to URL2 -> Response to Client
I commented url1 and invoked url2. url2 is a simple servlet which invokes url1 and gets the response. The servlets returns the same response back to the client but this time ajax/jquery returns parse error. When i alert (request.responseText), it exactly matches the response returned by URL1.
$.ajax({
//url: "http://abc1.com", // Line 1
url: "http://abc2.com", // Line 2
data: {param1, param2},
dataType: "jsonp",
type: "GET",
async:false,
success: function(parsed_json) {
alert("Success");
},
error: function (request, status, error) {
alert("Error" + error);
alert(request.responseText);
}
The Servlet is just a layer in between which copies the content of the input stream to the output stream.
InputStream input = new URL(url).openStream();
resp.setContentType("application/json");
// Apache commons IOUtils to copy
IOUtils.copy(input, resp.getOutputStream());
resp.getOutputStream().flush();
I manually verified the json-string-response and it appears to be the same.
What could be the problem ?
Here’s one possible issue: I note that
dataTypeisjsonp, which is different thanjson. jQuery could conceivably throw an error if the request came back as JSON when it was expecting JSON-P. Does changing thedataTypetojsonchange anything?Here’s the difference, by the way:
JSON-P is used primarily for communicating with remote websites. Since browsers can’t send AJAX requests to other domains for security reasons, a JSON-P “AJAX request” will actually add something like this to the DOM:
If the remote site supports JSON-P, it will return something like this:
Then your
myCallbackfunction is called with the data from the remote site – ta da!jQuery handles all this callback business automatically if you say
dataTypeisjsonp, but, if you sayjsonpbut don’t wrap the data in a callback, (as I understand it) jQuery will notice that the script loaded and throw an error since the callback never fired.Or maybe it is JSON-P and I’m just wasting by breath. Anyway. Just in case 🙂