MVC中处理Json和JS中处理Json对象

作者:袖梨 2022-06-25

public JsonResult Test()

 
{
JsonResult json = new JsonResult
{
Data = new
{
Name = "zzl",
Sex = "male",
}
};
return Json(json);
}
 
public JsonResult TestList()
{
List userList = new List
{
new User{Name="zzl",Email="[email protected]"},
new User{Name="zhz",Email="[email protected]"},
};
JsonResult json = new JsonResult
{
Data = userList
};

return Json(json);

 
//return Json(json, JsonRequestBehavior.AllowGet);//前台AJAX如果是GET用这句
//什么时候用GET请求呢,当我们直接在浏览器中输入网址时,其实就是一个GET请求
//如果我们直接输入/Home/TestList这个网址,它会提示我们下载这个JSON格式的文档
}

前台调用:
 

第二种列表的方法,也可以这样来实现更加简单:
 
public JsonResult TestList()
 
{
List userList = new List
{
new User{Name="zzl",Email="[email protected]"},
new User{Name="zhz",Email="[email protected]"},
new User{Name="zql",Email="[email protected]"},
};

return Json(userList);

//return Json(userList, JsonRequestBehavior.AllowGet);//前台AJAX如果是GET用这句
 
}
$.ajax({
 
url: "/Home/TestList",
dataType: "json",
cache: false,
data: null,
type: "POST",
success: function (data) {
var msg = "
";
for (var i = 0, length = data.length; i < length; i++) {
msg += "
";
}
msg += "
NameEmail
" + data[i].Name + ""
+ data[i].Email + "
";
$("#msg2").html(msg);
}

});

注意看红色的部分,是否是更简单了呢!哈哈
 
 

 

纯JS进行操作:
var arr = [{ "name": "zzl", "sex": "男" }, { "name": "lr", "sex": "女"}];
for (var i = 0; i < arr.length;i++ ) {
document.write(arr[i].name);
}

相关文章

精彩推荐