ajax--Client Access WebService basic usage

Source: Internet
Author: User

Before learning aps.net, I learned to use the server to access the WebService method, then implemented an example:Web server simulation on-line shopping, today to learn ASP. Ajax learns the way the client accesses Webserivice directly. The way the client accesses webserver directly reflects Ajax's idea of asynchronously refreshing the data.

Client Access WebService Basics
steps to create a WebService end:

1. Create a aps.net WebService

2. Add tag [scriptservice]

3. Write WebService method, and add tag [webmethod]

< Span style= "line-height:30px" > steps for Client access WebService

1. An ASMX file is introduced into the inserted scrptmanager.

2. Incoming parameters

3. Write a method as a successful callback function.

4. You can also write an error handler as a failed callback function.

Here is a small example of their own writing: The approximate requirement is to enter two numbers on the client, to call the Webservic-side division method, if the successful output operation results, if the error input output error specific content. (especially simple)

Webservic End

   public class Divsion:System.Web.Services.WebService    {        [WebMethod] public        int Getdivison (int a, int b)// Division operation        {            return a/b;        }        [WebMethod]        public int TimeOut ()        {            thread.sleep ();  Set sleep time            return 0;        }    }

Client

<body> <form id= "Form1" runat= "Server" > <div> <asp:scriptmanager id= "ScriptManager1" Run at= "Server" > <Services> <asp:servicereference path= "Divsion.asmx"/> &            lt;/services> </asp:ScriptManager> <script language= "javascript" type= "Text/javascript" > Provides the default error handling callback function, which is called after all subsequent methods have been loaded, so Failedcallback's life begins at the end of the//webapplication1.divsion.set_de            Faultfailedcallback (Failedcallback);            Set to 1 seconds after timeout WebApplication1.divsion.set_timeout (1000);                function getdivsion () {var a = document.getElementById ("Text1"). Value;                var B = document.getElementById ("Text2"). Value;            WebApplication1.divsion.getDivison (a,b,getsuccess,getfailed);            } function Getsuccess (result)//succeeded after callback function {alert (result); } function getfailedError handling {var message = String.Format ("Timeout: {0}\nmessage: {1}\nexc Eptiontype: {2}\nstacktrace: {3} ", Error.get_timedout (), Error.get_message (), Error.get_exceptiontype (), error.get_                StackTrace ());            alert (message);  } </script> </div> </form> <input id= "Text1" type= "text"/> Divided by <input Id= "Text2" type= "text"/> <input id= "Button1" type= "button" value= "equals" onclick= "getdivsion ()"/></body>

Run results

When entering two integers:


When the divisor is 0: error handling is thrown


Client Access Pagemethod Basics
The
difference between this approach and the previous one is that:

1. This method can only be placed on the server side (the back-end code of the ASPX) in the methods that will be called.

2. only static methods can be exposed and the specific control content of the page cannot be obtained

3. use the WebMethod tag to release.

Client Access server-side steps:

1. Introduce Scrptmanager to the page and modify Srciptmangeer set in enablepagemethods=true.

2. Access via Pagemethods.methodname.

3. Write a method as a callback function for success or failure.

Here is a simple little example: the approximate requirement is that the client calls this method when the server-side writes the method to get the current time.

Server-side

[Webmethod]public Static DateTime GetCurrentTime () {              //The return Datetime.utcnow is displayed based on the time at which the client is present        ;}

Client

/head><body>    <form id= "Form1" runat= "Server" >    <%--enablepagemethods Method Assignment is not limited--%>< Asp:scriptmanager id= "ScriptManager1" runat= "Server" enablepagemethods= "true"/><input type= "button" value= " Get Current Time "onclick=" GetCurrentTime () "/>    <script language=" javascript "type=" Text/javascript "> function GetCurrentTime () {    //getcurrenttimesucceeded is a callback function Pagemethods.getcurrenttime (getcurrenttimesucceeded );} function getcurrenttimesucceeded (Result) {alert (result);} </script>    </form></body>

Client Agent usage details
full signature of the function call

Invoke (Arg1,.. Argn,onsuccessed,onfailed,usercontext)

Arg1: Parameters

Onsuccessed: function that was successfully called

Onfailed: A function that failed to call, or is a function of error handling.

UserContext: Call method, accept method to continue processing method, is different method, so the argument can put the passed parameters into the userContext

callback function Full Signature

Onsuccessed/onfailed (Result,usercontext,methodname)

WebService level default Properties
Timeout
: Timeout
defaultusercontext: The default usercontext

Defaultsuccessededcallback : Default Success callback function

defaultFailedCallback: default error handling method

Summary:

This part is just beginning to learn, it's a bit slow to learn, but there's a lot of interest in this one, because asynchronous transmission is really a lot more efficient. Of course, through this part of the client access to Webserivice learning, but also more and more sense of the net AJAX framework of the powerful.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.