@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>GetDate</title>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(function () {
$('#btnGetDate').click(function () {
$.post('/Ajax/GetDate', {}, function (data) {
alert(data);
})
});
$('#btnGetList').click(function () {
$.post('/Ajax/GetList', {}, function (data) {
var serverData = $.parseJSON(data);
var length = serverData.length;
for (var i = 0; i < length; i++) {
$('#dv').append(serverData[i].UserName);
}
})
});
$('#btnGetList2').click(function () {
$.post('/Ajax/GetList2', {}, function (data) {
for (var i = 0; i < data.length; i++) {
$('#dv').append(data[i].UserName);
}
})
});
});
</script>
</head>
<body>
<div>
<input type="button" id="btnGetDate" name="name" value="获取时间" />
<input type="button" id="btnGetList" name="name" value="获取列表" />
<input type="button" id="btnGetList2" name="name" value="获取列表2" />
<div id="dv"></div>
</div>
</body>
</html>
/**********************************************************************************************/
using Mvc190212.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcTest1.Controllers
{
public class AjaxController : Controller
{
UserInfoDbContext db = new UserInfoDbContext();
// GET: Ajax
public ActionResult Index()
{
return View();
}
public ActionResult GetDate()
{
return Content(DateTime.Now.ToShortDateString());
}
//第一种方式,返回Json字符串,在js里面需要解析
public ActionResult GetList()
{
var userInfoList = db.UserInfo.Where(u => true).ToList();
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
return Content(js.Serialize(userInfoList));
}
//第二种方式,直接返回Json数组
public ActionResult GetList2()
{
var userInfoList = db.UserInfo.Where(u => true).ToList();
return Json(userInfoList);
}
//第三种方法,MVC专用
public ActionResult ShowCreate()
{
return View();
}
public ActionResult AddUserInfo()
{
return Content(DateTime.Now.ToShortDateString());
}
}
}
/*****************************************************************************/
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ShowCreate</title>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script>
function AfterAdded(data) {
alert(data);
}
</script>
</head>
<body>
<div>
@using (Ajax.BeginForm("AddUserInfo", "Ajax", new AjaxOptions
{
Confirm = "确定要添加吗?",
HttpMethod = "post",
UpdateTargetId = "dv",
InsertionMode = InsertionMode.InsertBefore,
LoadingElementId = "dv2",
OnSuccess="AfterAdded"
}))
{
<input type="submit" value="添加用户" />
}
<div id="dv"></div>
<div id="dv2" style="display:none">正在添加...</div>
</div>
</body>
</html>