javascript - 获取 OpenLayers GET 请求的 responseText JSON 元素

标签 javascript json gis openlayers responsetext

我正在尝试使用OpenLayers.Request.GET从URL加载JSON格式的数据。

这是请求(注意:url 工作正常,它带来 JSON 格式的数据):

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
});

对于处理程序,我尝试获取 request.responseText 并在 json 文件中显示特定键,如下所示:

var obj;

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

这是我的 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"}}}

但我收到此错误:(注意 TestPrint.html:506 是警报行)

 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

最佳答案

您不解析您的响应,您需要使用的函数是 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
}

您的错误是由于您尝试访问未定义的“所有 JSON”.features (您是否听说过具有 features 属性的字符串(它应该是一个列表)?我真的不这么认为:P

关于javascript - 获取 OpenLayers GET 请求的 responseText JSON 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16781357/

相关文章:

javascript - Twig json_encode 与实体对象和集合(Symfony3)

json - 以不区分大小写的方式使用 json_populate_recordset

javascript - 将 R data.frame 转换为 Javascript 数组

c# - 墨卡托投影和缩放

python - 如何使用Shapely提取内部多边形坐标?

javascript - 如何在本地存储中存储字体大小

javascript - Sequelize js : create/update with foreign key

javascript - 动态创建的输入字段的奇怪行为

ruby-on-rails - 停止在哈希 Ruby on Rails 中编码的字符串

javascript - 创建一个JS购物车。请告知添加到购物车