default.aspx 代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#ajax1").click(function () {
var data = "{}";
$.ajax({
url: "/WebService.asmx/getmsg",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: data,
success: function (json) {
console.info(json.d);
alert(json.d);
}
});
}); $("#ajax2").click(function () {
var data = "{'name':'"+$("#name").val()+"'}";
$.ajax({
url: "/WebService.asmx/getname",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: data,
success: function (json) {
console.info(json.d);
alert(json.d);
}
});
}); $("#ajax3").click(function () {
var data = "{'name':'" + $("#name1").val() + "'}";
$.ajax({
url: "/default.aspx/getname",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: data,
success: function (json) {
console.info(json.d);
alert(json.d);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="无参" id="ajax1"/><br/>
<input type="text" name="name" id="name"/>
<input type="button" value="带参" id="ajax2" />
<br />
<input type="text" name="name" id="name1"/>
<input type="button" value="后台方法Ajax调用" id="ajax3"/>
</div>
</form>
</body>
</html>
default.aspx.cs 代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
[System.Web.Services.WebMethod]
public static string GetName(string name)
{
return "调用后台方法:"+name;
}
}
WebService.cs 代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services; /// <summary>
/// WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService { public WebService () { //如果使用设计的组件,请取消注释以下行
//InitializeComponent();
} [WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public string GetMsg()
{
return "信息";
}
[WebMethod]
public string GetName(string name)
{
return name;
}
}