使用jQuery ajax请求访问嵌套JSON数据报Cannot read property [0]错误
问题原因及修复方案
核心错误原因
你遇到的*Cannot read property [0] of undefined*报错,本质是response.features为空数组/未定义,直接按下标取值触发异常,具体有3个问题点:
- 查询条件语法错误:你请求的ArcGIS FeatureServer接口中,
Source字段是字符串类型,拼接查询条件时没有给值加单引号,导致查询匹配不到任何数据,返回的features为空。原URL里的where=Source=+ $scope.location.Source 要改成where=Source='+ $scope.location.Source +',给值包裹单引号。
- 查询条件语法错误:你请求的ArcGIS FeatureServer接口中,
- Angular指令语法错误:HTML里的
ng - model、ng - click中间多了空格,不符合AngularJS的指令书写规范,会导致输入框的双向绑定失效,无法正确获取你输入的SourceID。
- Angular指令语法错误:HTML里的
- 缺少容错判断:成功回调里没有先判断返回结果是否存在、
features数组是否有值,直接按下标取值,只要查询无结果就会触发报错,另外空的error回调会隐藏接口请求的报错信息,不方便排查问题。
- 缺少容错判断:成功回调里没有先判断返回结果是否存在、
修复后的代码
HTML部分
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.5.0/build/ol.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <div class="pagewrapper"> <div id="header"></div> <div id="controls"> <h1>Controls</h1> <div ng-app="myApp" ng-controller="locationController"> Enter SourceID(from 0001 to 0012): <input ng-model="location.Source"> <button class="btn btn-default" ng-click="location.getElevation()">Search</button> <p>Elevation: {{location.ele}}</p> </div> </div> </div>
JS部分
var mainApp = angular.module("myApp", []); mainApp.controller('locationController', function($scope) { $scope.location = { Source: '0001', getElevation: function() { $.ajax({ // 给Source的查询值加单引号 url: 'https://services.arcgis.com/Sf0q24s0oDKgX14j/arcgis/rest/services/gpsData/FeatureServer/0/query?where=Source=\'' + $scope.location.Source + '\'&outFields=*&f=geojson', method: 'GET', success: function(response) { // 加容错判断,避免无结果时报错 if (response && response.features && response.features.length > 0) { $scope.location.ele = response.features[0].properties.ele; } else { $scope.location.ele = '未查询到对应数据'; } $scope.$apply(); }, error: function(xhr, err) { console.error('请求出错:', err); $scope.location.ele = '请求失败,请重试'; $scope.$apply(); } }) } } })
内容的提问来源于stack exchange,提问作者giozzz
相关产品推荐
相关产品推荐

