标签:arp mil table pre body div $.ajax span wget
事实上,MVC中已经很好的封装了Json,让我们很方便的进行操作,而不像JS中那么复杂了。
MVC中:
public JsonResult Test()
{
JsonResult json = new JsonResult
{
Data = new
{
Name = "zzl",
Sex = "male",
}
};
return Json(json);
}
public JsonResult TestList()
{
List<User> userList = new List<User>
{
new User{Name="zzl",Email="bfyxzls@sina.com"},
new User{Name="zhz",Email="zhanghangzheng@sina.com"},
};
JsonResult json = new JsonResult
{
Data = userList
};
return Json(json);
//return Json(json, JsonRequestBehavior.AllowGet);//前台AJAX如果是GET用这句
//什么时候用GET请求呢,当我们直接在浏览器中输入网址时,其实就是一个GET请求
//如果我们直接输入/Home/TestList这个网址,它会提示我们下载这个JSON格式的文档
}
前台调用:
<script>
$.ajax({
url: "/Home/Test",
dataType: "json",
cache: false,
data: null,
type: "POST",
success: function (data) {
alert(data.Data.Name);
}
});
$.ajax({
url: "/Home/TestList",
dataType: "json",
cache: false,
data: null,
type: "POST",
success: function (data) {
var msg = "";
for (var i = 0, length = data.Data.length; i < length; i++) {
msg += "<DiV>Name:" + data.Data[i].Name + ",Email:" +
data.Data[i].Email + "</div>";
}
$("#msg2").html(msg);
}
});
</script>
第二种列表的方法,也可以这样来实现更加简单:
public JsonResult TestList()
{
List<User> userList = new List<User>
{
new User{Name="zzl",Email="bfyxzls@sina.com"},
new User{Name="zhz",Email="zhanghangzheng@sina.com"},
new User{Name="zql",Email="zql1980.happy@sina.com"},
};
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 = "<table border=1><thead><tr><td>Name</td><td>Email</td>
</tr></thead><tbody>";
for (var i = 0, length = data.length; i < length; i++) {
msg += "<tr><td>" + data[i].Name + "</td><td>"
+ data[i].Email + "</td></tr>";
}
msg += "</body></table>";
$("#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);
}
标签:arp mil table pre body div $.ajax span wget
原文地址:http://www.cnblogs.com/sjqq/p/7355131.html