gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property 'Name' of undefined

转载 作者:行者123 更新时间:2023-11-30 11:30:21 24 4
gpt4 key购买 nike


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

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


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

  [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>

查看文件
查看显示 map 的文件并通过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>

最佳答案

问题出在这些行中:

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

JSON.stringify() 将 javascript object 转换为 json 文本并将其存储字符串

您不需要迭代一个 json 字符串,因为您需要迭代一个集合

您必须直接迭代数据

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

POST方法的响应由ajax成功回调自动解析。

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

关于javascript - 未捕获的类型错误 : Cannot read property 'Name' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46476767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com