【问题标题】:Uncaught TypeError: Cannot read property 'Name' of undefined未捕获的类型错误:无法读取未定义的属性“名称”
【发布时间】:2018-03-10 15:32:00
【问题描述】:


我正在开发一个网页,该网页显示开放的街道地图并通过经纬度坐标从 SQL Server 数据库中获取数据 我使用 asp.net mvc 并给我这个错误

未捕获的类型错误:无法读取未定义的属性“名称”
我在哪里通过 javascript 绑定数据库中的数据


型号
这个模型数据我创建了 GetMap(),它通过 Json 函数从数据库返回数据

  [HttpPost]
        public JsonResult GetMap()
        {
            var data1 =(from p in db.Map
                    select new
                    {
                        Name = p.Name,
                        Latitude = p.Latitude,
                        Logitude = p.Logitude,
                        Location = p.Location,
                        Description = p.Description,
                        Id = p.Id
                    }).ToList().Select(res => new Map
                    {
                        Name = res.Name,
                        Latitude = res.Latitude,
                        Logitude = res.Logitude,
                        Location = res.Location,
                        Description = res.Description,
                        Id = res.Id


                    });
            return Json(data1, JsonRequestBehavior.AllowGet);
        } 
</pre> 

查看文件
查看显示地图并通过 Json 函数返回数据的文件

    <div id="mapid" style="height:600px"></div>
    <script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script>
        $(document).ready(function () {

        var map = L.map('mapid').setView([31.291340, 34.244190], 13);

        L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);





            $.ajax({
                type: "POST",
                url: '/Maps/GetMap',
                success: function (data) {
                    var result = JSON.stringify(data);

                    for (var i = 0; i < result.length; ++i) {

                        var popup =
                            '<b>Name:</b> ' + data[i].Name +
                         '<br/><b>Latitude:</b> ' + data[i].Latitude +
                           '<br/><b>Longitude:</b> ' + data[i].Logitude +
                        '<br/><b>Location:</b> ' + data[i].Location;


                        L.marker([data[i].Latitude, data[i].Logitude])
                            .bindPopup(popup)
                           .addTo(map); 

                    }

                },
                error: function (xhr) {

                    console.log(xhr.responseText);
                    alert("Error has occurred..");
                }
            });
        });

    </script>

【问题讨论】:

  • 检查成功函数中的for循环,迭代到result.length,但result应该是data。错误消息表明某些data[i] 未定义。
  • 试试 $.parseJSON();还要检查您获得的数据
  • 您的 linq 查询中发生了什么?您可以删除.ToList() 之后的Select 部分。而且,如果这些是 Map 对象中的唯一属性,您不妨摆脱整个查询,只做 return Json(db.Map.ToList())
  • 我的回答对你有用吗?

标签: javascript asp.net asp.net-mvc


【解决方案1】:

问题在于以下几行:

 var result = JSON.stringify(data);
 for (var i = 0; i < result.length; ++i) {

JSON.stringify() 将 javascript object 转换为 json 文本和 stores 字符串

您不需要迭代 json 字符串,因为您需要迭代 collection

你必须直接迭代data

 for (var i = 0; i < data.length; i++) {}

POST方法的响应被ajax成功callback自动解析。

此外,在执行 POST 请求时,您不需要 JsonRequestBehavior.AllowGet 属性。这仅对 GET 动词是必需的,因为它可以保护您免受涉及 JSON 请求的非常具体的攻击。

【讨论】:

  • 是的,你可以迭代一个字符串! s = "abc"; for (i = 0; i &lt; s.length; i++) { console.log(s[i])}
  • @jpaugh,我更新为json string。更具体。
  • 谢谢!我可以看到您找到了正确的问题,但请仔细观察:OP 试图在循环内引用 data[i],而不是 result[i]。循环根本不需要使用result
  • @Alexandru-IonutMihai 我想你仍然可以......唯一的区别是你会得到额外的“”。 var s =“测试”; var s1 = JSON.stringify(s); for(var i =0;i
【解决方案2】:

你在这里生成一个字符串

var result = JSON.stringify(data);

然后循环直到字符串长度,也就是这个字符串中的字符数(不是你的json数组长度)

for (var i = 0; i < result.length; ++i) { }

字符串长度会超过你的 json 数组长度。

所以只需修复您的循环以使用正确的变量。

for (var i = 0; i < data.length; ++i) {

}

也无需致电Json.stringify。简单地循环遍历 json 数组。

或者,您可以使用$.each

success: function (data) {
  $.each(data,function(indx,item)
  {
    console.log(item.Name);
  }
}

您的服务器代码也可以简化。无需进行两次投影。

[HttpPost]
public JsonResult GetMap()
{
        var data1 =db.Map.Select(res => new Map
                              {
                                Name = res.Name,
                                Latitude = res.Latitude,
                                Logitude = res.Logitude,
                                Location = res.Location,
                                Description = res.Description,
                                Id = res.Id
                             }).ToList();
    return Json(data1);
} 

当你的action方法用[HttpPost]装饰时,你不需要指定JsonRequestBehavior.AllowGet

【讨论】:

    【解决方案3】:

    此错误表示您正在尝试引用给定对象 (undefined) 上不存在的字段(名称)。您的代码中有三个地方引用了 Name 字段:

    • p.Name
    • res.Name
    • data[i].Name

    所以presdata[i] 之一在您尝试引用Name 属性时未定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      • 2021-12-22
      • 2015-01-06
      • 2017-07-26
      相关资源
      最近更新 更多