Jquery也是实现Ajax

本文介绍了如何使用Jquery的get和post方法实现Ajax请求。通过示例代码展示了如何从控制器获取时间和通过表单提交用户数据,并更新页面内容。讨论了在禁用JavaScript时可能出现的问题及解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在上一篇介绍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="#" οnclick="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)
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
Model
using System.ComponentModel.DataAnnotations;

namespace MvcAjax.Models
{
public class UserModel
{
[Display(Name = "Username")]
public string UserName { get; set; }

[Display(Name = "Email")]
public string Email { get; set; }

[Display(Name = "Description")]
public string Desc { get; set; }
}
}
Controller
[HttpPost]
public ActionResult SaveUser(UserModel userModel)
{
//Save User Code Here
//......

return Content("Save Complete!");
}
以上代码实现了Jquery POST提交数据的方法。
通过查看以上两种Jquery方式的Ajax实现方法,和之前AJax HTML Helper比较可以发现其实Controller都是相同的。
采用Jquery方式提交数据的的主要实现方案就是通过Jquery的get或者post方法,发送请求到MVC的controller中,然后处理获取的response,更新到页面中。
注意点:
无论是使用超链接和form方式来提交请求,javascript的方法始终都有一个返回值false,用来防止超链接的跳转或者是form的实际提交。
这个地方就会出现一个疑问:
如果针对该页面禁止了Javascript脚本,那么该页面就是跳转或者是form就是提交,返回的ActionResult处理就会出现问题了。
这个时候就需要在Controller中判断该请求是否是Ajax请求,根据不同的情况返回不同的ActionResult:
[HttpPost]
public ActionResult SaveUser(UserModel userModel)
{
//Save User Code Here
//......

if (Request.IsAjaxRequest())
return Content("Save Complete!");
else
return View();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值