如何从服务器到javascript数组获取对象数组 [英] How to get object array from server to javascript array
本文介绍了如何从服务器到javascript数组获取对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从我的控制器获取对象数组,
i可以看到返回的数据,但是javascript array(arr)仍然是空的....
这里是我的代码示例,我做错了什么?
JS :
Hi,
I am trying to get object array from my controller,
i can see that data is returned, but the javascript array (arr) remains empty....
here is a sample of my code, what am i doing wrong?
JS:
var arr = [];
var onSuccess = function (data) {
arr = data;
};
$.ajax({
type: 'GET',
url: 'MyController/GetCurrentAlarms',
traditional: true,
success: function (data) { onSuccess(data); },
});
控制器:
Controller:
public JsonResult GetCurrentAlarms()
{
List<Alarm> list = new List<Alarm>();
Alarm alm = new Alarm()
{
ID = 1,
Name = "Alarm1"
};
list.Add(alm);
alm = new Alarm()
{
ID = 2,
Name = "Alarm2"
};
list.Add(alm);
alm = new Alarm()
{
ID = 3,
Name = "Alarm3"
};
list.Add(alm);
return Json(list.ToArray(), JsonRequestBehavior.AllowGet);
}
推荐答案
.ajax({
type:' GET',
url:' MyController / GetCurrentAlarms',
traditional: true ,
成功: function (数据){onSuccess(data);},
});
.ajax({ type: 'GET', url: 'MyController/GetCurrentAlarms', traditional: true, success: function (data) { onSuccess(data); }, });
控制器:
Controller:
public JsonResult GetCurrentAlarms()
{
List<Alarm> list = new List<Alarm>();
Alarm alm = new Alarm()
{
ID = 1,
Name = "Alarm1"
};
list.Add(alm);
alm = new Alarm()
{
ID = 2,
Name = "Alarm2"
};
list.Add(alm);
alm = new Alarm()
{
ID = 3,
Name = "Alarm3"
};
list.Add(alm);
return Json(list.ToArray(), JsonRequestBehavior.AllowGet);
}
试试这个
Try this
var _url = '@Url.Action("GetCurrentAlarms" ,"Home")';
.ajax({
url:_url,
dataType: json,
类型: GET ,
contentType:' application / json; charset = utf-8',
成功: function (数据){
onSuccess(数据);
},
错误:函数(xhr){
调试器;
alert(' 错误跨度>);
}
});
});
var arr = [];
var onSuccess = function (data){
arr = data;
alert(arr);
};
.ajax({ url: _url, dataType: "json", type: "GET", contentType: 'application/json; charset=utf-8', success: function (data) { onSuccess(data); }, error: function (xhr) { debugger; alert('error'); } }); }); var arr = []; var onSuccess = function (data) { arr = data; alert(arr); };
这篇关于如何从服务器到javascript数组获取对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文