要实现Javascript调用页面静态方法,有下面几个前提
1. 方法必须是静态的
2. 方法必须标记为WebMethod
3. 方法没有参数
4. 不能从客户端传递数据过来(因为静态方法,无法读取到这些数据)--待进一步核实
5. 客户端必须用$.ajax,而不能用$.post
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<%@ Import Namespace="JSONHelper" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Web" %>
<!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 runat="server">
<title></title>
<script src="jquery-1.3.2-vsdoc.js" type="text/javascript"></script>
<script src="json2.js" type="text/javascript"></script>
<script runat="server">
//这段代码是运行在服务器端的(C#代码),为了能在javascript中调用,需要标记为WebMethod
[System.Web.Services.WebMethod]
public static string HelloWorld()
{
return "Hello,world";
}
[System.Web.Services.WebMethod]
public static Employee GetEmployee()
{
return new Employee()
{
Id = 1,
Name = "chenxizhang"
};
}
[System.Web.Services.WebMethod]
public static Employee PostEmployee()
{
//这个方法是接受一个Employee输入,然后返回一个Employee
//注意,这个方法不会成功,因为该方法是静态方法,所以其实是没有办法通过Request获取到有关的数据的
var emp = HttpContext.Current.Request["data"].ToJsonObject<Employee>();
return emp;
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
</script>
<script type="text/javascript" language="javascript">
//这段脚本是运行在客户端的
function CallHelloWorld() {
$.ajax({
type: "POST",
contentType: "application/json",
url: "default.aspx/HelloWorld",
data: "{}",
dataType: 'json',
success: function(result) {
$("#info").append(result.d); //如果返回简单类型,则用一个d表示的
$("#info").append("<br />");
}
});
}
function GetEmployee() {
$.ajax({
type: "POST",
contentType: "application/json",
url: "default.aspx/GetEmployee",
data: "{}",
dataType: 'json',
success: function(result) {
$("#info").append("员工编号为:" + result.d.Id + ",姓名为:" + result.d.Name);
$("#info").append("<br />");
}
});
}
function PostEmployee() {
//在客户端构造一个对象
var emp = {
Id: 1,
Name: "chenxizhang"
};
$.ajax({
type: "POST",
contentType: "application/json",
url: "default.aspx/PostEmployee",
data: { data: JSON.stringify(emp) },
dataType: 'json',
success: function(result) {
$("#info").append("员工编号为:" + result.d.Id + ",姓名为:" + result.d.Name);
$("#info").append("<br />");
},
error: function(o, e) {
alert(e);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="button" value="调用页面静态方法(简单类型)" onclick="CallHelloWorld()" />
<input type="button" value="调用页面静态方法(复杂类型)" onclick="GetEmployee()" />
<input type="button" value="调用页面静态方法(提交复杂类型)" onclick="PostEmployee()" />
<div id="info">
</div>
</form>
</body>
</html>