Jquery调用Asp.Net WebService和form 提交到Handler方式
Html代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>无标题页</title>
</head>
<script type="text/javascript" src="javsscript/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#send").click(function() {
var username = $("#username").val();
var age = $("#age").val();
$.ajax({
type: "post", //访问WebService使用Post请求
contentType: "application/json;utf-8", //webservice会返回Json类型
url: "IbeaconWebService.asmx/SendEmail", //调用webservice使用地址和方法名称组合 ---url/方法名
data: "{username:'" + username + "',age:'" + age + "'}", //要传入得参数注意格式
datatype: "json",
success: function(msg) { //回调函数 msg返回值
$("#message").html(msg.d);//返回结果显示在div中
}
});
return false;
});
});
</script>
<body>
<form action="IbeaconHandler.ashx" method="get">
<table>
<tr>
<td>
姓名:
</td>
<td>
<input id="username" name="username" type="text" />
</td>
</tr>
<tr>
<td>
年龄:
</td>
<td>
<input id="age" name="age" type="text" />
</td>
</tr>
<tr>
<td>
<input type="button" value="ajax发送" id="send" />
</td>
<td>
<input type="submit" value="form提交" onclik="submit()" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="message">
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
页面截图:
后台Webservice代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
/// <summary>
///IbeaconWebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class IbeaconWebService : System.Web.Services.WebService {
public IbeaconWebService () {
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public string SendEmail(string username,int age) {
return "发送成功!姓名:"+username+"年龄:"+age;
}
}
Handler代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <%@ WebHandler Language="C#" Class="IbeaconHandler" %>
2
3 using System;
4 using System.Web;
5
6 public class IbeaconHandler : IHttpHandler {
7
8 public void ProcessRequest (HttpContext context) {
9 context.Response.ContentType = "text/html";
10 string name = context.Request["username"].ToString();
11 string age = context.Request["age"].ToString();
12 //context.Response.Write("你好:"+name);
13 context.Response.Write("发送成功!姓名:"+name+"年龄:"+age);
14 }
15
16 public bool IsReusable {
17 get {
18 return false;
19 }
20 }
21
22 }