【发布时间】:2014-06-25 15:00:43
【问题描述】:
我一直在使用硬编码的 JSON 对象:
var resuts = [{id: 1, Code: "Code A"}, {id: 2, Code: "Code B"}]
然后我将迭代这个对象,按索引调用项目并使用 .length:
for (var i = 0; i < resuts.length; i++) {
console.log('id:' + resuts[i].id + ' | ' + 'Code:' + resuts[i].Code}
现在我想从服务器中提取这些数据,所以我创建了一个对象来处理属性并拥有这个操作方法:
public ActionResult GetResults()
{
string json = JsonConvert.SerializeObject(new
{
results = new List<Question>()
{
new Question { id = 1, Code = "Code A},
new Question { id = 1, Code = "Code B}
}
});
return Json(new { data = json }, JsonRequestBehavior.AllowGet);
}
我用这个 AJAX 调用它:
function GetResultsJSON() {
$.ajax({
type: 'GET',
url: '/Home/GetResults/',
dataType: 'json',
traditional: true,
success: function (data) {
results = data;
},
error: function (data) {
alert('Error.');
}
})
};
现在我的结果对象包含:
"{" results ":[{" id ":1," Code ":" Code A "},{" id ":1," Code ":" Code B "}]}"
现在我在尝试使用长度属性或按索引调用项目时遇到 JavaScript 错误。根据我阅读的内容,我认为我最初的硬编码对象只是一个数组,但是,我必须对从控制器返回的 JSON 进行不同的处理。
谁能建议返回我最初使用的数组格式或处理此处返回的 JSON 格式的最佳方法?我尝试过类似
$.each(data, function(i, obj) {
alert(obj.name);
});
但这返回未定义。任何帮助都会很棒。
【问题讨论】:
标签: c# jquery asp.net-mvc json