Get element of a responseText JSON of an OpenLayers GET request

Asma.O picture Asma.O · May 28, 2013 · Viewed 13.5k times · Source

I am trying to use OpenLayers.Request.GET to load data from url in JSON format.

Here's the request (note: url works fine, it brings data in JSON format):

var request = OpenLayers.Request.GET({
    url: "http://localhost:8080/geoserver/wrspc/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=wrspc:layer1&maxFeatures=60&outputFormat=json",
    callback: handler
});

for the handler I tried to get the request.responseText and show a specific key in the json file like this:

var obj;

function handler(request) {
    obj = request.responseText;
    alert (obj.features[0].indicator);
}

and here's my JSON:

 {"type":"FeatureCollection","features":[{"type":"Feature","id":"titid","geometry":{"type":"MultiPolygon","coordinates":[[[[3694.7863290442,3749.0463695516],[9328.2052648721,3756.61081112875],[3694.18117371807,3861.9059202327],[9340.68659347435,3834.4171230714],[9334.7863290442,3749.0463695516],[3634.7863290442,3839.0463695516]]]]},"geometry_name":"the_geom","properties":{"name1":"asme","number":9130,"indicator":"20","gid":939}}],"crs":{"type":"EPSG","properties":{"code":"2684"}}}

but I get this error: (note the TestPrint.html:506 is the alert line)

 Uncaught TypeError: Cannot read property '0' of undefined TestPrint.html:506
 GeoExt.form.FormPanel.listeners.actioncomplete TestPrint.html:506
 h.Event.fire ext-all.js:21
 h.Observable.fireEvent ext-all.js:21
 (anonymous function) ext-all.js:21
  h.Event.fire ext-all.js:21
  h.Observable.fireEvent ext-all.js:21
  Ext.form.BasicForm.Ext.extend.afterAction ext-all.js:21
  GeoExt.form.SearchAction.Ext.extend.handleResponse SearchAction.js:147
  OpenLayers.Protocol.WFS.v1.OpenLayers.Class.handleRead OpenLayers.js:843
  (anonymous function) OpenLayers.js:413
  (anonymous function) OpenLayers.js:62
  OpenLayers.Request.runCallbacks OpenLayers.js:509
  d.onreadystatechange OpenLayers.js:508
  b.dispatchEvent OpenLayers.js:751
  c OpenLayers.js:744
  _object.onreadystatechange OpenLayers.js:748

Answer

Niccolò Campolungo picture Niccolò Campolungo · May 28, 2013

You don't parse your response, the function you need to use is JSON.parse:

function handler(request) {
    //responseText is the raw JSON string, you need to convert it to a JS object
    //use var keyword to define new variables inside your function scope
    var obj = JSON.parse(request.responseText);
    //note that indicator is not a valid features property, you should change it!
    alert(obj.features[0].indicator); //return undefined, change it maybe to .type
}

Your error is given by your attempt to access "all your JSON".features which is undefined(have you ever heard about a string that has features property(it should be a list)? I don't really think so :P