mot*_*ana 0 asp.net-mvc jquery json
我有这个代码:
var mapcity = new Array([]);
$.ajax({
type: 'GET',
url: '/home/DrawMap',
dataType: 'json',
success: function (data) {
var len = data.length;
for (var i = 0; i < len; i++) {
// mapcity['' + data[i].name + ''] = { center: new google.maps.LatLng(data[i].x, data[i].y), population: data[i].population, name: '' + data[i].name + '' };
mapcity['' + data[i].name + ''] = { center: new google.maps.LatLng(data[i].x, data[i].y), population: data[i].population, name: ''+data[i].name+'' };
//newarr[i] = data[i].name;
alert(mapcity[0].population)
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
这是我的代码的一部分,这是来自控制器的功能:
public ActionResult DrawMap() {
string data = "[{ 'x':31.949454,'y': 35.932913,'population':50000,'name':'amman'},{ 'x':33.79,'y': 33.39,'population':100000,'name':'Zarqa'}]";
data=data.Replace("'","\"");
return this.Content(data, "application/json");
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,它从控制器获取JSON数据,但不将其保存到mapcity变量中!它什么都不做.我该如何解决它以及我做错了什么?
您永远不应该像您一样手动构建JSON,但始终使用JSON序列化程序:
public ActionResult DrawMap()
{
var data = new[]
{
new
{
x = 31.949454,
y = 35.932913,
population = 50000,
name = "amman",
},
new
{
x = 33.79,
y = 33.39,
population = 100000,
name = "Zarqa",
}
};
return Json(data, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
此外,您已mapcity
在成功处理程序之外声明了您的变量,这导致我认为您在$ .ajax调用之后立即尝试使用其值,这显然是不可能的,因为AJAX本身就是异步的.这意味着成功回调可以在以后执行,$ .ajax调用立即返回.
因此,使用此变量的唯一安全位置是INSIDE成功函数:
$.ajax({
type: 'GET',
url: '/home/DrawMap',
success: function (data) {
var mapcity = {};
var len = data.length;
for (var i = 0; i < len; i++) {
mapcity['' + data[i].name + ''] = { center: new google.maps.LatLng(data[i].x, data[i].y), population: data[i].population, name: ''+data[i].name+'' };
}
}
});
Run Code Online (Sandbox Code Playgroud)
你还有另一个问题.您将mapcity
变量声明为array(new Array([])
),然后尝试将非整数索引插入其中:
mapcity['' + data[i].name + '']
Run Code Online (Sandbox Code Playgroud)
在javascript中声明一个数组时,它只能有0个基于整数的索引.因此,您可以将其声明为javascript对象var mapcity = {};
或仅使用整数索引.
归档时间: |
|
查看次数: |
13140 次 |
最近记录: |