我正在尝试使用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
答案 0 :(得分:2)
您无法解析您的回复,您需要使用的功能是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
答案 1 :(得分:0)
您可以通过以下方式访问“指标”对象(它嵌套在属性功能下):
obj.features[0].properties['indicator']
在这种情况下,您可以使用online json parser来了解您的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"
}
}
}
答案 2 :(得分:0)
我弄明白了,现在它适用于eval
函数
obj = eval('(' + request.responseText + ')');
和alert(obj.features[0].properties['indicator']);
。