Reputation:
I'm a bit new to JS and I'm having some problems with my code.
I have Ajax request to the server, from which I get the response. Since it's cross-domain request, I'm using JSONP.
$.ajax({
url: "***",
contentType: 'application/javascript',
dataType: "jsonp",
jsonpCallback: "parseResponse"
})
.done(function (response) {
doSomething();
})
.fail(function (error)) {
console.log(error);
}
Response that I get:
parseResponse({...})
My problem is with understanding how parseResponse callback works. With this code I SOMETIMES get
"Uncaught ReferenceError: parseResponse is not defined".
But part of responses get through OK (in .done function I filter response and from there, I fill a table).
How should be parseResponse defined correctly?
EDIT: "parseResponse" is default callback set by Geoserver service.
Example of response:
parseResponse({"type":"FeatureCollection","totalFeatures":"unknown","features":[],"crs":null})
Typically features property array would be filled with some data.
Upvotes: 1
Views: 3101
Reputation: 1074335
Remove jsonpCallback: "parseResponse"
from your ajax
call. That lets jQuery handle all the work for you. (It creates a unique function name, creates the function, passes the name to the endpoint, and cleans up the function when done.)
Also remove the contentType: "application/javascript"
. You're not sending JavaScript code to the server.
$.ajax({
url: "***", // <== Make sure this DOESN'T have ?callback= on it
dataType: "jsonp"
})
.done(function(response) {
doSomething();
})
.fail(function(error)) {
console.log(error);
});
According to your comments, the target service (Geoserver) requires a ridiculous option for specifying the JSONP callback: format_options=callback:name
. That doesn't play nicely with ajax
at all (and I've never seen such obtuse support for JSONP before).
To handle it while not using a hardcoded name (because hardcoded names are a bad idea, you can't overlap calls), we have to play silly games like this:
var callbackName = "myJSONPCallback" + Date.now() + Math.floor(Math.random() * 100000);
$.ajax({
url: "//the-url?format_options=callback:" + callbackName,
// Include ----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// in the URL
dataType: "jsonp",
jsonp: false,
jsonpCallback: callbackName
})
.done(function(response) {
doSomething();
})
.fail(function(error)) {
console.log(error);
});
See ajax
documentation (linked above) for details of the jsonp
and jsonpCallback
options.
Upvotes: 2