[英]Get element of a responseText JSON of an OpenLayers GET request
我正在尝试使用OpenLayers.Request.GET
以JSON格式从url加载数据。
这是请求(注意: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
特性(它应该是一个列表)我真的不这么认为:P
您可以通过以下方式访问“指标”对象(它嵌套在属性功能下):
obj.features[0].properties['indicator']
在这种情况下,您可以使用在线json解析器来了解您的json结构。
你的json:
{
"type":"FeatureCollection",
"features":[
{
"type":"Feature",
"id":"titid",
"geometry":{
"type":"MultiPolygon",
"coordinates":[
[]
]
},
"geometry_name":"the_geom",
"properties":{
"name1":"asme",
"number":9130,
"indicator":"20",
"gid":939
}
}
],
"crs":{
"type":"EPSG",
"properties":{
"code":"2684"
}
}
}
我想通了,现在它与eval
函数一起工作,
obj = eval('(' + request.responseText + ')');
和alert(obj.features[0].properties['indicator']);
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.