您的位置:首页 > Web前端 > JQuery

MVC异步AJAX的三种方法(JQuery的Get方法、JQuery的Post方法和微软自带的异步方法)

2017-12-13 09:03 393 查看
异步是我们在网站开发过程中必不可少的方法,MVC框架的异步方法也有很多,这里介绍三种方法:

一.JQuery的Get方法

view



@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.8.2.js"></script>
@*我们使用JQ的异步方式获取后台的时间*@
<script type="text/javascript">
$(function() {
$("#btnJQ").click(function() {
//从后台获取时间
$.get("/Ajax/GetDate",{}, function(data) {
alert(data);
});
});
});
</script>
</head>
<body>
<div>
<input type="button" id="btnJQ" value="获取服务器的时间"/>

</div>
</body>
</html>


二.JQuery的Post方法

view



@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.8.2.js"></script>
@*我们使用JQ的异步方式获取后台的时间*@
<script type="text/javascript">
$(function() {
$("#btnJQ").click(function() {
//从后台获取时间
$.ajax({
url: "/Ajax/GetDate",//请求地址
type: "POST",//请求的类型
success: function(data) {  //成功后的回调函数
alert(data);
},
data:"id=2&name=222"//传递的数据
});
});
});
</script>
</head>
<body>
<div>
<input type="button" id="btnJQ" value="获取服务器的时间"/>

</div>
</body>
</html>


三.微软自带的异步方法

view



@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>MicrosoftAjax</title>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript">
function afterSuccess(data) {
//alert(data);
}
</script>
</head>
<body>
<div>
@using (Ajax.BeginForm("GetDate", "Ajax", new AjaxOptions(){
Confirm  ="您是否要提交吗?",  //用来在提交前做个提醒是否提交
HttpMethod = "Post",   //提交的方式是get还是post
InsertionMode = InsertionMode.Replace,  //这个插入的模式InsertAfter:在后面追加    InsertBefore:在现有文本之前    Replace:替换
UpdateTargetId = "result",  //更新对应目标Id的标签的内容
OnSuccess="afterSuccess",   //执行成功之后执行的方法
LoadingElementId = "loading"}  //在没有返回结果之前显示的图片
)
)
{
<div>
用户名:<input type="text" name="UserName" /><br />
密码:<input type="text" name="Pwd"/><br />
<input type="submit" value="提交"/>
</div>
}
<div id="result">

</div>

<div id="loading" style="display:none">
<img src="~/Content/ico_loading2.gif" />
</div>
</div>
</body>
</html>


三个异步对应的Controllers



public class AjaxController : Controller
{
//
// GET: /Ajax/

public ActionResult Index()
{
return View();
}

public ActionResult GetDate()
{
//让网站睡眠1秒钟
System.Threading.Thread.Sleep(1000);
return Content(DateTime.Now.ToString());
}

public ActionResult MicrosoftAjax()
{
return View();
}

}


 

注意:采用Jquery方式提交数据的的主要实现方案就是通过Jquery的get或者post方法,发送请求到MVC的controller中,然后处理获取的response,更新到页面中。

       微软自带的方法更加全面实用,合理运用其属性值,会得到意向不到的效果。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: