[GIS] How to get JSON from Geoserver using AJAX request

geoserverjavascriptjquerywfswfs-t

I am building a web mapping application using Leaflet and a sort of customized WFS-T API to place and retrieve features from PostGIS. I have the script for putting features in PostGIS tables down solid, and I've managed to publish my tables as WFS services using Geoserver. My problem–which seems simple enough–is how to import those vector features back onto my map. I figured it would be easiest to go with the JSON option Geoserver provides, but when I make the below request using jQuery:

    $.ajax({
    url: "http://localhost:8090/geoserver/cite/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=cite:markers&maxFeatures=50&outputFormat=json&callback=?",
    dataType: "jsonp",
    success: function() {
        //
    }
}).done(function ( data ) {
    console.log(data);
});

or:

    $.getJSON("http://localhost:8090/geoserver/cite/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=cite:markers&maxFeatures=50&outputFormat=json&jsoncallback=?", function(data){ 
     console.log(data);
});

I get the following error:

SyntaxError: invalid label [Break On This Error]    
{"type":"FeatureCollection","features":[{"type":"Feature","id":"markers.1","geom...

Now, I know that these two functions are equivalent; what would seem to be a mismatch between specifying json in the url string and jsonp as the datatype is in fact correct because Javascript interprets the response as Javascript rather than true JSON. I've also figured out from reading other forum posts that the problem is the json script is not being properly contained in an object variable; the syntax error is due to missing parentheses on either side — ({jsonobject}) — like so. My question is, how the heck do I fix the syntax to get JavaScript to work with it? Obviously everything I want is coming through–it's just breaking because of a stupid syntax error that I can't figure out how to overcome. Any help on this would be much appreciated.

Best Answer

GeoServer has its own convention for JSONP callbacks, which is described here (coudn't find it mentioned in the official docs).

So I quickly hacked a jsfiddle showing how you can use it with jQuery, just remember to set the url, workspace and layers so that they point to your geoserver.

Related Question