• jQuery & WebMethod 不及格的程序员


     SVC webservice

    $.ajax({
                type: "post",
                url: "/Service1.svc/getName",
                data: '{"name":[0,1,2],"imageBuffer":[0,1,2]}',
                contentType: 'application/json; charset=utf-8',
                dataType: "json",
                success: function (data)
                {
                    alert(data);
                },
                error: function (data)
                {
                    alert(data.statusText);
                }
            });
    
    this.message = this.httpInput.DecodeBufferedMessage(new ArraySegment<byte>(buffer.Array, 0, offset), inputStream);
                            this.requestException = this.httpInput.ProcessHttpAddressing(this.message);
    
    System.Text.Encoding.ASCII.GetString(new byte[]{123,34,110,97,109,101,34,58,94,48,44,49,44,50,93,44,34,105,109,97,103,101,66,117,102,102,101,114,34,58,91,48,44,49,44,50,93,125})
    //->   "{\"name\":^0,1,2],\"imageBuffer\":[0,1,2]}"

    c# Form Post System.Text.Encoding.ASCII.GetString(new byte[]{110,111, 61, 97,98,99,100}) "no=abcd" $.ajax( { type: "post", url: './MerchantPaymentWaiting.aspx', data: {"no": strNo}, WebMethod, contentType: "application/json; charset=utf-8", dataType: "json", private static IDictionary<string, object> GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer) { string str = new StreamReader(context.Request.InputStream).ReadToEnd(); if (string.IsNullOrEmpty(str)) { return new Dictionary<string, object>(); } return serializer.Deserialize<IDictionary<string, object>>(str); }

    JQuery直接调用asp.net后台WebMethod方法

     参考:

    JQuery直接调用asp.net后台WebMethod方法

    AJAX向后台WebMethod static方法传递数组并接收 

    利用JQuery的$.ajax()可以很方便的调用asp.net的后台方法。
    [WebMethod]   命名空间

    1、无参数的方法调用, 注意:1.方法一定要静态方法,而且要有[WebMethod]的声明
    后台<C#>:

    [csharp] view plain copy
     
    1. using System.Web.Script.Services;     
    2.    
    3. [WebMethod]     
    4. public static string SayHello()     
    5. {     
    6.      return "Hello Ajax!";     
    7. }  

     

    前台<JQuery>:

    [javascript] view plain copy
     
    1. $(function() {     
    2.     $("#btnOK").click(function() {     
    3.         $.ajax({     
    4.             //要用post方式     
    5.             type: "Post",     
    6.             //方法所在页面和方法名     
    7.             url: "data.aspx/SayHello",     
    8.             contentType: "application/json; charset=utf-8",     
    9.             dataType: "json",     
    10.             success: function(data) {     
    11.                 //返回的数据用data.d获取内容     
    12.                 alert(data.d);     
    13.             },     
    14.             error: function(err) {     
    15.                 alert(err);     
    16.             }     
    17.         });     
    18.    
    19.         //禁用按钮的提交     
    20.         return false;     
    21.     });     
    22. });  

     

    2、带参数的方法调用

    后台<C#>:

    [csharp] view plain copy
     
    1. using System.Web.Script.Services;  
    2.    
    3. [WebMethod]  
    4. public static string GetStr(string str, string str2)  
    5. {  
    6.     return str + str2;  
    7. }  

     

    前台<JQuery>:

    [javascript] view plain copy
     
    1. $(function() {     
    2.     $("#btnOK").click(function() {     
    3.         $.ajax({     
    4.             type: "Post",     
    5.             url: "data.aspx/GetStr",     
    6.             //方法传参的写法一定要对,str为形参的名字,str2为第二个形参的名字     
    7.             data: "{'str':'我是','str2':'XXX'}",     
    8.             contentType: "application/json; charset=utf-8",     
    9.             dataType: "json",     
    10.             success: function(data) {     
    11.                 //返回的数据用data.d获取内容     
    12.                   alert(data.d);     
    13.             },     
    14.             error: function(err) {     
    15.                 alert(err);     
    16.             }     
    17.         });     
    18.    
    19.         //禁用按钮的提交     
    20.         return false;     
    21.     });     
    22. });  

    3、带数组参数的方法调用

      前台

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
        <script src="http://code.jquery.com/jquery-1.10.1.js"></script>
        <script>
            $(document).ready(function () {
                var myCars = new Array();
                myCars[0] = "Saab";
                myCars[1] = "Volvo";
                myCars[2] = "BMW";
     
                $.ajax({
                    type: "POST",
                    url: "<%=Request.Url.AbsolutePath%>/Concat",
                    data: JSON.stringify({ arr: myCars }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert(response.d);
                    },
                    failure: function () {
                        alert("fail");
                    }
                });
            });
        </script>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    [System.Web.Script.Services.ScriptService]
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
     
        [WebMethod]
        public static string Concat(List<string> arr)
        {
            string result = "";
            for (int i = 0; i < arr.Count; i++)
            {
                result += arr[i];
            }
            return result;
        }
    }

    4、返回数组方法的调用

    后台<C#>:

    [csharp] 
    1. using System.Web.Script.Services;  
    2.    
    3. [WebMethod]  
    4. public static List<string> GetArray()  
    5. {  
    6.     List<string> li = new List<string>();  
    7.    
    8.     for (int i = 0; i < 10; i++)  
    9.         li.Add(i + "");  
    10.    
    11.     return li;  
    12. }  

     

    前台<JQuery>:

     
    1. $(function() {     
    2.     $("#btnOK").click(function() {     
    3.         $.ajax({     
    4.             type: "Post",     
    5.             url: "data.aspx/GetArray",     
    6.             contentType: "application/json; charset=utf-8",     
    7.             dataType: "json",     
    8.             success: function(data) {     
    9.                 //插入前先清空ul     
    10.                 $("#list").html("");     
    11.    
    12.                 //递归获取数据     
    13.                 $(data.d).each(function() {     
    14.                     //插入结果到li里面     
    15.                     $("#list").append("<li>" + this + "</li>");     
    16.                 });     
    17.    
    18.                 alert(data.d);     
    19.             },     
    20.             error: function(err) {     
    21.                 alert(err);     
    22.             }     
    23.         });     
    24.    
    25.         //禁用按钮的提交     
    26.         return false;     
    27.     });     
    28. });   
    29. /// <reference path="jquery-1.4.2-vsdoc.js"/>  
    30. $(function() {  
    31.     $("#btnOK").click(function() {  
    32.         $.ajax({  
    33.             type: "Post",  
    34.             url: "data.aspx/GetArray",  
    35.             contentType: "application/json; charset=utf-8",  
    36.             dataType: "json",  
    37.             success: function(data) {  
    38.                 //插入前先清空ul  
    39.                 $("#list").html("");  
    40.    
    41.                 //递归获取数据  
    42.                 $(data.d).each(function() {  
    43.                     //插入结果到li里面  
    44.                     $("#list").append("<li>" + this + "</li>");  
    45.                 });  
    46.    
    47.                 alert(data.d);  
    48.             },  
    49.             error: function(err) {  
    50.                 alert(err);  
    51.             }  
    52.         });  
    53.    
    54.         //禁用按钮的提交  
    55.         return false;  
    56.     });  
    57. });  
     

    Jquery ajax传递复杂参数给WebService

    Entity:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.Serialization;
     
    namespace Entity
    {
        [DataContract]
        public class User
        {
            [DataMember]
            public string Name
            {
                get;
                set;
            }
     
            [DataMember]
            public int Age
            {
                get;
                set;
            }
        }
    }

    WebService:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using Entity;
     
    namespace JQuery.Handler
    {
     
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        [System.Web.Script.Services.ScriptService]
        public class UserService1 : System.Web.Services.WebService
        {
     
            [WebMethod]
            public string ComplexType(User hero,List<User> users)
            {
                return hero.Name + " has " + users.Count + " people!";
            }
        }
    }

    Html:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Ajax</title>
        <script src="../Scripts/jquery-1.6.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function () {
                $("#btnWeb").click(function () {
                    $.ajax(
                    {
                        type: "post",
                        url: "../Handler/UserService.asmx/ComplexType",
                        dataType:"json",
                        contentType:"application/json",
                        data: '{"hero": {"Name":"zhoulq","Age":27},"users":[{"Name":"zhangs","Age":22},{"Name":"wangw","Age":26},{"Name":"liuj","Age":25},
                               {"Name":"luos","Age":24}]}',
                        success: function (data) { $("#web").text(data.d); }
                    });
                });
            });
        </script>
    </head>
    <body>
        <input id="btnWeb" type="button" value="请求WebService" /><label id="web"></label>
    </body>
    </html>

    Exposing Web Services to Client Script

    The AJAX functionality of ASP.NET enables you to call ASP.NET Web services (.asmx files) from the browser by using client script. This enhances the user experience for the Web application. The page can call server-based methods without a postback and without refreshing the whole page, because only data is transferred between the browser and the Web server.

    This topic describes how to make a Web service available to JavaScript running in the browser.

    ASP.NET automatically creates JavaScript proxy classes for Web services. Proxy classes are derived from the Sys.Net.WebServiceProxy class. You can call a Web service method by calling the corresponding method of the JavaScript proxy class. For more information, see Calling Web Services from Client Script.

    Making Web Services Accessible from Script

    In order for a Web service to be accessed from script, it must be an .asmx Web service whose Web service class is qualified with the ScriptServiceAttribute attribute. Individual methods to be called from script must be qualified with the WebMethodAttribute attribute.

    The following example shows these attributes in Web service code.

    C#
    [ScriptService]
    public class SimpleWebService : System.Web.Services.WebService
    {
        [WebMethod]
        public string EchoInput(String input)
        {
            // Method code goes here.
        }
    }
    

    To enable Web service calls from script, you must register the ScriptHandlerFactory HTTP handler in the application's Web.config file. The handler processes calls made from script to .asmx Web services. The following example shows the Web.config element for adding the handler.

     Note

    These configuration settings are already part of the Web.config file template for any new AJAX-enabled Web sites that you create in Microsoft Visual Studio 2005.

    <system.web>
      <httpHandlers>
        <remove verb="*" path="*.asmx"/> 
        <add verb="*" path="*.asmx" 
          type="System.Web.Script.Services.ScriptHandlerFactory"
           validate="false"/>
      </httpHandlers>
    <system.web>
    

    For Web service calls that are not issued from ASP.NET AJAX script, the ScriptHandlerFactory handler delegates the call to the default handler, which uses SOAP instead of JSON format. The delegation is performed automatically and you do not have to take any action unless you want to disable the use of the SOAP protocol for the Web services. In that case, you must enter the following configuration setting in the Web.config file.

    <system.web>
      <webServices>
        <protocols>
          <clear/>
        </protocols>
      </webServices>
    </system.web>
    

    Exposing Web Services to Client Script in an ASP.NET Web Page

    To enable an .asmx Web service to be called from client script in an ASP.NET Web page, you must add a ScriptManager control to the page. You reference the Web service by adding an asp:ServiceReference child element to the ScriptManager control and then setting the server reference path attribute to the URL of the Web service. The ServiceReference object instructs ASP.NET to generate a JavaScript proxy class for calling the specified Web service from client script.

    The following example shows how to enable a Web service named SimpleWebService.asmx to be called from script in an ASP.NET Web page.

    <asp:ScriptManager runat="server" ID="scriptManager">
      <Services>
        <asp:ServiceReference
           path="~/WebServices/SimpleWebService.asmx" />
      </Services>
    </asp:ScriptManager>
    

    The ServiceReference object can reference a Web service only in the same domain as the page. The Web service path can be relative, application relative, domain relative, or absolute. For absolute paths, you must make sure that the path is in the same domain.

    When a page that contains this ScriptManager control is rendered, the page creates a JavaScript proxy class for the SimpleWebService.asmx Web service. The proxy class has methods that correspond to the Web methods in the SimpleWebService.asmx service. The page also contains JavaScript proxy classes that correspond to server data types that are used as input parameters or return values for the Web service methods. This enables you to write client script that initializes these parameters, and to pass them to the method call.

    The InlineScript property of the ServiceReference object specifies how the JavaScript proxy class is included in the page. If InlineScript is set to false (the default), the proxy script is obtained by making a separate request. This option is better when multiple pages reference the same service and when browser caching is enabled.

    If InlineScript is set to true, the proxy class script is included as an inline script block in the page. This can improve performance by reducing the number of network requests. This is especially true if there are many service references in the page and other pages do not reference the same service. If InlineScript is set to true, you must use a relative path. If the path is domain-relative, it must refer to the same Web application.

    The following examples show a simple Web service that is called from script that displays the user's input and returns the current server time. The following example shows the page that makes service calls through client script.

    C#
    <%@ Page Language="C#" %>
    
    <!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 id="Head1" runat="server">
            <style type="text/css">
                body {  font: 11pt Trebuchet MS;
                        font-color: #000000;
                        padding-top: 72px;
                        text-align: center }
    
                .text { font: 8pt Trebuchet MS }
            </style>
    
            <title>Simple Web Service</title>
    
                <script type="text/javascript">
    
                // This function calls the Web Service method.  
                function EchoUserInput()
                {
                    var echoElem = document.getElementById("EnteredValue");
                    Samples.AspNet.SimpleWebService.EchoInput(echoElem.value,
                        SucceededCallback);
                }
    
                // This is the callback function that
                // processes the Web Service return value.
                function SucceededCallback(result)
                {
                    var RsltElem = document.getElementById("Results");
                    RsltElem.innerHTML = result;
                }
    
            </script>
    
        </head>
    
        <body>
            <form id="Form1" runat="server">
             <asp:ScriptManager runat="server" ID="scriptManager">
                    <Services>
                        <asp:ServiceReference path="SimpleWebService.asmx" />
                    </Services>
                </asp:ScriptManager>
                <div>
                    <h2>Simple Web Service</h2>
                        <p>Calling a simple service that echoes the user's input and 
                            returns the current server time.</p>
                        <input id="EnteredValue" type="text" />
                        <input id="EchoButton" type="button" 
                            value="Echo" onclick="EchoUserInput()" />
                </div>
            </form>
    
            <hr/>
    
            <div>
                <span id="Results"></span>
            </div>   
    
        </body>
    
    </html>
    

    The following example shows the service that is called through the client script.

    C#
    <%@ WebService Language="C#" Class="Samples.AspNet.SimpleWebService" %>
    
    using System;
    using System.Web;
    using System.Web.Services;
    using System.Xml;
    using System.Web.Services.Protocols;
    using System.Web.Script.Services;
    
    namespace Samples.AspNet
    {
    
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [ScriptService]
        public class SimpleWebService : System.Web.Services.WebService
        {
    
            [WebMethod]
            public string EchoInput(String input)
            {
                string inputString = Server.HtmlEncode(input);
                if (!String.IsNullOrEmpty(inputString))
                {
                    return String.Format("You entered {0}. The "
                      + "current time is {1}.", inputString, DateTime.Now);
                }
                else
                {
                    return "The input string was null or empty.";
                }
            }
    
        }
    
    }
    

    Calling Static Methods in an ASP.NET Web Page

    You can add static page methods to an ASP.NET page and qualify them as Web methods. You can then call these methods from script in that page as if they were part of a Web service, but without creating a separate .asmx file. To create Web methods in a page, import the System.Web.Services namespace and add a WebMethodAttribute attribute to each static method that you want to expose. The page methods must be defined in the page that is performing the page-method call.

    To be able to call static page methods as Web methods, you must set the EnablePageMethods attribute of the ScriptManager control to true.

    The following examples show how to call static page methods from client script to write and read session-state values. The following example shows page methods.

    C#
    <%@ Page Language="C#" %>
    <%@ Import Namespace="System.Web.Services" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    
    <script runat="server">
    
        [WebMethod]
        // Get session state value.
        public static string GetSessionValue(string key)
        {
            return (string)HttpContext.Current.Session[key];
        }
    
        [WebMethod]
        // Set session state value.
        public static string SetSessionValue(string key, string value)
        {
            HttpContext.Current.Session[key] = value;
            return (string)HttpContext.Current.Session[key];
        }
    
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    <head id="Head1" runat="server">
    
        <title>Using Page Methods with Session State</title>
        <style type="text/css">
                body {  font: 11pt Trebuchet MS;
                        font-color: #000000;
                        padding-top: 72px;
                        text-align: center }
                .text { font: 8pt Trebuchet MS }
        </style>
    </head>
    
    <body>
    
        <h2>Using Page Methods with Session State</h2>
    
        <form id="form1" runat="server">
            <asp:ScriptManager ID="ScriptManager1" 
                runat="server" EnablePageMethods="true">
                <Scripts>
                    <asp:ScriptReference Path="PageMethod.js"/>
                </Scripts>
            </asp:ScriptManager>
        </form>
    
         <center>
             <table>
                <tr align="left">
                    <td>Write current date and time in session state:</td>
                    <td>
                        <input type="button" 
                            onclick="SetSessionValue('SessionValue', Date())" 
                            value="Write" />
                    </td>
                </tr>
                <tr align="left">
                    <td>Read current date and time from session state:</td>
                    <td>         
                        <input type="button" 
                            onclick="GetSessionValue('SessionValue')" 
                            value="Read" />
                    </td>
                </tr>
            </table>           
    
        </center>
    
        <hr/>
    
        <span style=" color: rgb(163, 21, 21);">"ResultId"></span>
    
    </body>
    
    </html>
    

    The following example shows script is used to make page methods calls.

    // PageMethods.js
    
    var displayElement;
    
    // Initializes global variables and session state.
    function pageLoad()
    {
        displayElement = $get("ResultId");
        PageMethods.SetSessionValue("SessionValue", Date(), 
            OnSucceeded, OnFailed);
    }
    
    // Gets the session state value.
    function GetSessionValue(key) 
    {
        PageMethods.GetSessionValue(key, 
            OnSucceeded, OnFailed);
    }
    
    //Sets the session state value.
    function SetSessionValue(key, value) 
    {
        PageMethods.SetSessionValue(key, value, 
            OnSucceeded, OnFailed);
    }
    
    // Callback function invoked on successful 
    // completion of the page method.
    function OnSucceeded(result, userContext, methodName) 
    {
        if (methodName == "GetSessionValue")
        {
            displayElement.innerHTML = "Current session state value: " + 
                result;
        }
    }
    
    // Callback function invoked on failure 
    // of the page method.
    function OnFailed(error, userContext, methodName) 
    {
        if(error !== null) 
        {
            displayElement.innerHTML = "An error occurred: " + 
                error.get_message();
        }
    }
    
    if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
    

    For more information about session state, see ASP.NET Session State Overview.

    See Also

    Tasks

    Using the UpdatePanel Control with a Web Service

    Concepts

    Using Web Services in ASP.NET AJAX

    Using Web Services in ASP.NET AJAX

    Exposing WCF Services to Client Script

    Calling Web Services from Client Script

    Using Forms Authentication with ASP.NET AJAX

    Using Profile Information with ASP.NET AJAX


    this._xmlHttpRequest = new XMLHttpRequest();
            this._xmlHttpRequest.onreadystatechange = this._onReadyStateChange;
            var verb = this._webRequest.get_httpVerb();
            this._xmlHttpRequest.open(verb, this._webRequest.getResolvedUrl(), true );
            this._xmlHttpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            if (headers) {
                for (var header in headers) {
                    var val = headers[header];
                    if (typeof(val) !== "function")
                        this._xmlHttpRequest.setRequestHeader(header, val);
                }
            }
            if (verb.toLowerCase() === "post") {
                if ((headers === null) || !headers['Content-Type']) {
                    this._xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
                }
                if (!body) {
                    body = "";
                }
            }
            var timeout = this._webRequest.get_timeout();
            if (timeout > 0) {
                this._timer = window.setTimeout(Function.createDelegate(this, this._onTimeout), timeout);
            }
            this._xmlHttpRequest.send(body); //"{"buffer":[214,208,206,196,49,50,51],"image":[214,208,206,196,49,50,51]}"
            this._started = true;
    [WebMethod]
            public static byte[] testMethod(byte[] buffer)
            {
                return System.Text.Encoding.GetEncoding("gb2312").GetBytes(System.Text.Encoding.GetEncoding("gb2312").GetString(buffer));
            }
    <form id="form1" runat="server">
            <asp:ScriptManager ID="script01" runat="server" EnablePageMethods="true"></asp:ScriptManager>
            
            <script language="javascript">
                function getBytes(chrList)
                {
                    var bytes = [];
                    for (var i = 0; i < chrList.length; i++)
                    {
                        c = "";
                        ch = chrList.charAt(i);
                        window.execScript("c = Hex(asc(ch))", "vbscript");
                        bytes.push(c);
                    }
                    return bytes;
                }
           parseInt("00000011",2) //3
                var byteBuffer = []; //getBytes("中文0123") -> ["D6D0", "CEC4", "30", "31", "32", "33"]
                byteBuffer.push(0xD6, 0xD0, 0xCE, 0xC4);
                byteBuffer.push("0123".charCodeAt(1) & 0xFF);
                byteBuffer.push("0123".charCodeAt(2) & 0xFF);
                byteBuffer.push("0123".charCodeAt(3) & 0xFF);
                var exec_result = PageMethods.testMethod(byteBuffer,
                    function (result, userContext, methodName)
                    {
                        if (result!=null)
                        {                       
                            debugger;
                        }
                        alert(result);
                    },
                    function (result, userContext, methodName)
                    {
                        if(result != null)
                            debugger;
                    }, "testUser");
            </script>
  • 相关阅读:
    Ubuntu上使用Latex
    Ubuntu18.04 解压文件名乱码的解决方法
    Android 编译 opencv
    android 使用编译好的sdk
    https协议加密原理介绍(一)
    java 面试题目 class.forName和load的区别
    给进程设置环境变量
    Maven 编译jdk配置
    Docker积累
    潜谈单例模式
  • 原文地址:https://www.cnblogs.com/ioriwellings/p/9035628.html
Copyright © 2020-2023  润新知