javascript调用asp.net后置代码方法
aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="PriceSystem_temp_Default" %>
<!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>
</head>
<script src="../js/jquery-1.5.1.min.js" type="text/javascript"></script>1:2:3: <script>4: $(function() {5: PageMethods.Hello("张三", function(e) {6: alert(e);7: });8: })</script>
<body>
<form id="form1" runat="server">
<asp:scriptmanager ID="Scriptmanager1" EnablePageMethods="true" runat="server"></asp:scriptmanager>
<div>
</div>
</form>
</body>
</html>
cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Linq;
using System.Data;
using System.Web.Services;
public partial class PriceSystem_temp_Default : PageBase
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod(EnableSession = true)]
public static string Hello(string name)
{
return "hello," + name;
}
}
总结ASP.NET AJAX在客户端JavaScript中异步调用服务器端Web Service,我们需要:
1 为Web Service类或需要暴露给客户端的Web Service方法添加[ScriptService]属性;
2 为Web Service中需要暴露给客户端的方法添加[WebMethod]属性;
3 在页面中的ScriptManager控件中添加对该Web Service的引用;
4 在客户端使用如下JavaScript语法调用该Web Service:
[NameSpace].[ClassName].[MethodName](param1, param2,..., callbackFunction)
5 为客户端异步调用指定回调函数,在回调函数中接收返回值并进一步处理。
使用ASP.NET AJAX在客户端JavaScript中异步调用定义在ASP.NET页面中的方法,我们需要:
1 将该方法声明为公有(public);
2 将该方法声明为类方法(C#中的static,VB.NET中的Shared),而不是实例方法;
3 为该方法添加[WebMethod]属性;
4 将页面中ScriptManager控件的EnablePageMethods属性设置为true;
5 在客户端使用如下JavaScript语法调用该页面方法:
PageMethods.[MethodName](param1, param2,..., callbackFunction);
6 为客户端异步调用指定回调函数,在回调函数中接收返回值并进一步处理
浙公网安备 33010602011771号