Ajax表单提交 serialize()
前台代码:
<html>
<head>
<title></title>
<script src="js/jquery-1.11.2.js"></script>
</head>
<body>
<form id="myForm">
<label for="userName">用户:</label><input type="text" name="userName" id="userName" />
<label for="password">密码:</label><input type="text" name="password" id="password" />
<label for="mobile">电话:</label><input type="text" name="mobile" id="mobile" />
<select name="myselect">
<option value="1" selected>中国</option>
<option value="2">德国</option>
<option value="3">美国</option>
</select>
<input class="loginBtn" type="button" value="提交" />
</form>
</body>
</html>
<script type="text/javascript">
$(function () {
$('#userName,#password,#mobile').on('keyup', function (e) { //给#userName,#password,#mobile给三个元素绑定keyup事件,
if (e.keyCode == 13) { // 如果用户按下了回车键(回车键的keyCode就是13) 就模拟用户点击了.loginBtn提交按钮。触发提交事件
$('.loginBtn').trigger('click');
}
});
var data = $("#myForm").serialize();
$(".loginBtn").on("click", function () {
var data = $("#myForm").serialize();
$.ajax({
url: "ajaxFormHandler.ashx",
data: data,
success: function (data) {
alert(data);
}
})
})
});
</script>
后台代码(一般应用处理程序)ajaxFormHandler.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace JqueryUI
{
/// <summary>
/// ajaxFormHandler 的摘要说明
/// </summary>
public class ajaxFormHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
var userName = context.Request["userName"]; //接收用户传递过来的值
var mySelect = context.Request["mySelect"];
var pas = context.Request["password"];
var mobile = context.Request["mobile"];
//context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
}