Jquery也是实现Ajax
在上一篇介绍MVC中的Ajax实现方法的时候,曾经提到了除了使用Ajax HTML Helper方式来实现之外,Jquery也是实现Ajax的另外一种方案。
通过get方法实现AJax请求
View
<script type="text/javascript">
function GetTime() {
$.get("Home/GetTime", function (response) {
$("#myPnl").html(response);
});
return false;
}
</script>
<div id="myPnl" style="width: 300px; height: 30px; border: 1px dotted silver;">
</div>
<a href="#" onclick="return GetTime();">Click Me</a>
Controller
public ActionResult GetTime()
{
return Content(DateTime.Now.ToString());
}
通过post方法实现Form的Ajax提交
View
@model MvcAjax.Models.UserModel
@{
ViewBag.Title = "AjaxForm";
}
<script type="text/javascript">
$(document).ready(function () {
$("form[action$='SaveUser']").submit(function () {
$.post($(this).attr("action"), $(this).serialize(), function (response) {
$("#myPnl").html(response);
});
return false;
});
});
</script>
<div id="myPnl" style="width: 300px; height: 30px; border: 1px dotted silver;">
</div>
@using (Html.BeginForm("SaveUser", "Home"))
{
<table>
<tr>
<td>
@Html.LabelFor(m => m.UserName)
</td>
<td>
@Html.TextBoxFor(m => m.UserName)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(m => m.Email)
</td>
<td>
@Html.TextBoxFor(m => m.Email)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(m => m.Desc)
</td>
<td>
@Html.TextBoxFor(m => m.Desc)