Example of three methods (including two types of Ajax) in the JavaScript call background, javascriptajax

Source: Internet
Author: User

Example of three methods (including two types of Ajax) in the JavaScript call background, javascriptajax

Method 1: directly use <% = %> call (ASPX page)

The front-end JS Code is as follows:

<script type="text/javascript">       var methodStr = "<%=BehindMethod() %>";        alert(methodStr);  </script>

The code for the background method is as follows:

Public static string BehindMethod () {return "this is a background method ";}

Note:

1) Before BehindMethod (),PublicDo not forget the access modifier;

2) This method has limitations -- BehindMethod () is automatically called only when the ASPX page is loaded or sent back, and cannot be manually controlled.

Method 2: Use ajax to call

The front-end JS/jQuery code is as follows:

<Script type = "text/javascript"> var params = {ext: "p9hp"}; // parameter, note that the parameter name must be consistent with the parameter name of the background method $ (function () {$ ("# btnOk "). click (function () {$. ajax ({type: "POST", // request url: "AjaxDemo. aspx/GetImg ", // Request Path: page/method name data: params, // The dataType parameter:" text ", contentType:" application/json; charset = UTF-8 ", beforeSend: function (XMLHttpRequest) {$ ("# tips "). text ("wait for"); $ ("# imgFood "). attr ("src", "image/loading.gif") ;}, success: function (msg) {// success $ ("# imgFood "). attr ("src", eval ("(" + msg + ")"). d); $ ("# tips "). text ("Call method ended") ;}, error: function (obj, msg, e) {// alert ("OH, NO ") ;}}) ;}); </script>

Page HTML, the Code is as follows:

<Body> <form id = "form1" runat = "server"> <div> <label id = "tips"> </label>  <input value = "Click me, show you an image "type =" button "width =" 35px "id =" btnOk "/> </div> </form> </body>

The code of the ASPX background method is as follows:

[System. web. services. webMethod] public static string GetImg (string ext) {System. threading. thread. sleep (5000); // latency of 5 seconds for a bit of wait effect StringComparer SC = StringComparer. ordinalIgnoreCase; string [] extArr = new string [] {"php", "asp", "aspx", "txt", "bmp"}; bool f = extArr. any (s => SC. equals (s, ext); // determines whether the passed extension name exists if (f) {return "image/54222860.jpg";} return" image/star1.jpg ";}

Note:

1) before the background Method[System. Web. Services. WebMethod]Not less;

2) There is also a form of ajax, similar to the above, the difference is: Use. the general ashx processing program changes the url in the front-end JS/jQuery code to the general processing path of the Request/[Address Bar parameters] (the address bar parameters are determined based on actual needs ), for example, url: "AjaxDemo. ashx ". Then in AjaxDemo. ashx. cs public void ProcessRequest (HttpContext context ){...} write the relevant code, and finally use context. response. return the value in the form of Write ("Return Value.

Method 3: AjaxPro or Ajax Library (also ajax)

Step 1: Download AjaxPro. dll (or Ajax. dll) and add the reference to the project.

Step 2: modify Web. config and add the following code under the <system. web> node. The Ajax. dll and Ajaxpro. dll reference methods here are different. Be sure to pay attention to them.

<Configuration> <system. web> 

For IIS7. webServer> </system. add <add name = "ajax" verb = "POST, GET" path = "ajax/* To webServer> /*. ashx "type =" Ajax. pageHandlerFactory, Ajax "/>

Step 3: Perform runtime registration on the pages used by AjaxPro (such as AjaxDemo. aspx) in the Page_Load event. For example:

Protected void Page_Load (object sender, EventArgs e) {Ajax. utility. registerTypeForAjax (typeof (AjaxDemo); // Ajax. dll AjaxPro. utility. registerTypeForAjax (typeof (AjaxDemo); // Ajaxpro. dll}

Call the RegisterTypeForAjax method to generate the following javascript code on the page (you can also manually add the following javascript code on the page ):


<script type="text/javascript" src="ajax/common.ashx"></script><script type="text/javascript" src="ajax/NAMESPACE.CLASS,ASSEMBLYNAME.ashx"></script>

The bold part of the above CodeNAMESPACE. PAGECLASS,ASSEMBLYNAMEMeaning:

NAMESPACE. CLASS

Namespaces and Classes

ASSEMBLYNAME

Assembly name

Ajax can also support custom classes, but this class can be serialized, that is, before a custom class such as a User[Serializable()]

[Serializable ()]Public class User {private int _ userId; private string _ firstName; private string _ lastName; public int userId {get {return _ userId ;}} public string FirstName {get {return _ firstName;} public string LastName {get {return _ lastName;} public User (int _ userId, string _ firstName, string _ lastName) {this. _ userId = _ userId; this. _ firstName = _ firstName; this. _ lastName = _ lastName;} public User () {} [Ajax. ajaxMethod ()] or [AjaxPro. ajaxMethod ()] public User GetUser (int userId) {// Replace this with a DB hit or something :) return new User (userId, "Michael", "Schwarz ");} [Ajax. ajaxMethod ()] or [AjaxPro. ajaxMethod ()] public DataSet GetUserList (paramType1 param1, paramType2 param2 ,...) {// Replace this with a DB hit or something :) return a DataSet;
} [Ajax. ajaxMethod ()] or [AjaxPro. ajaxMethod ()] public DataTable GetUserList (paramType1 param1, paramType2 param2 ,...) {// Replace this with a DB hit or something :) return a DataTable;
}}

Then, the code for registering the proxy class with RegisterTypeForAjax on the call page must also be changed accordingly. The proxy class name is no longer a page class, but a custom class. The Code is as follows:

Protected void Page_Load (object sender, EventArgs e) {Ajax. utility. registerTypeForAjax (typeof (User); // Ajax. dll AjaxPro. utility. registerTypeForAjax (typeof (User); // Ajaxpro. dll}

Step 4: Write the server method and mark it with [Ajax. AjaxMethod]

Note:

1) the method should be writtenPublicOtherwise, the system prompts "This attribute or method is not supported" when calling in JS ";

2) If the server-side function needs to process the Session information, you must pass a parameter on the Ajax. AjaxMethod attribute of the server-side function that supports the Session, for example, [Ajax. AjaxMethod (HttpSessionStateRequirement. Read)]. Of course, it can also be Write or ReadWrite. We can choose this parameter as needed.

In the following example, we have a document management system. When a user edits a document, the document will be locked. Other users can modify the document only when the document is available. If you do not use Ajax, you need to wait for Refresh because you have to constantly check whether the document status is available. This is certainly not a good solution. It is easier to use the sessionstate support of ajax.

First, we write a function in the Document class. This function traverses the Document ID to find the Document you need, store it in the session, and return the Document that is not in use:

[Ajax.AjaxMethod(HttpSessionStateRequirement.Read)]public ArrayList DocumentReleased(){       if (HttpContext.Current.Session["DocumentsWaiting"] == null)       {             return null;       }       ArrayList readyDocuments = new ArrayList();       int[] documents = (int[])HttpContext.Current.Session["DocumentsWaiting"];       for (int i = 0; i < documents.Length; ++i)       {             Document document = Document.GetDocumentById(documents[i]);             if (document != null && document.Status == DocumentStatus.Ready)             {                     readyDocuments.Add(document);             }                }        return readyDocuments; }

We specify HttpSessionStateRequirement. Read in the property parameter. The following describes the result of using the javascript function:

<script type="text/javascript">function DocumentsReady_CallBack(response){      if (response.error != null)      {             alert(response.error);             return;      }      if (response.value != null && response.value.length > 0)      {             var div = document.getElementById("status");             div.innerHTML = "The following documents are ready!<br />";             for (var i = 0; i < response.value.length; ++i)             {                    div.innerHTML += "<a href=\"edit.aspx?documentId=" + response.value[i].DocumentId + "\">" + response.value[i].Name + "</a><br />";              }       }}</script>  <body onload="setTimeout('Document.DocumentReleased(DocumentsReady_CallBack)', 10000);">

After the page is loaded, the request is sent to the server function every 10 seconds. If yes, the callback function checks response and displays the latest result.

Step 5: Call the GetUser function of the User class in front-end JS. The Ajax encapsulation class will create a javascript function in the form similar to the GetUser function on the server. With a parameter, we call it in the form of "class name. function name (If it is AjaxPor. dll, it is called in the form of "namespace. Class Name. function name ".).

As the most basic function of Ajax, all we need to do is call this method and pass parameters, and then obtain the return value for subsequent processing. The Code is as follows:

<script type="text/javascript">    var response = User.GetUser(168);    alert(response.value);</script>

Ajax also has more powerful functions, which is why all client proxies (such as User. GetUser) have an additional custom attribute at the same time. This property is used to process the callback function of the server response:

<script type="text/javascript">function getUser(userId){    User.GetUser(userId, GetUser_CallBack);}function GetUser_CallBack(response){     if (response != null && response.value != null)     {          var user = response.value;          if (typeof(user) == "object")          {                         alert(user.FirstName + " " + user.LastName);          }     }}getUser(1);</script>

From the code above, we can see that we have added an additional parameter GetUser_CallBack for the GetUser function, which is the client function used to process the server response. This CallBack function accepts a response object with four key attributes:

Value

Return Value of server-side function execution (may be a string, custom object, or dataset)

Error

If an error occurs, an error message is returned.

Request

Original xmlHttpRequest request

Context

A context object

 

First, we should check whether an error occurs. You can implement this error attribute by throwing an exception in the server-side function. In the above example, a simple alert value is the value attribute. The request attribute can be used to obtain additional information (more about XmlHttpRequest ).

Note:

The returned value has three attributes (FirstName, LastName, and UserId) Like the server object ).

In the instance, we return a User-class object in the server function. What response types does Ajax support?

Ajax supports many types besides the User class types returned by the preceding GetUser function. It supports integer, string, double, boolean, DateTime, DataSet, and DataTable, as well as simple custom types and arrays. Other types return strings in ToString mode.

The returned DataSet is like a real. net Dataset. Suppose there is a table tag with id userinfo on the page. We can display it on the client using the following method:

<script type="text/javascript">function getUserList(userId){    User.GetUserList(param1, param2, ..., GetUserList_CallBack);}function GetUserList_CallBack(response){     var ds = response.value;     if (ds != null && typeof(ds) == "object" && ds.Tables != null)     {          $("#userinfo").empty();          var rowsLength = ds.Tables[0].Rows.length;          if(rowsLength > 0)          {                for(var i = 0; i < rowsLength; i++)                {                      var UserRow = ds.Tables[0].Rows[i];                      $("#userinfo").append('<tr>');                      $("#userinfo").append('<td>[Ajax.AjaxMethod()]public string Test1(string name, string email, string comment){ string html = ""; html += "Hello " + name + "<br>"; html += "Thank you for your comment <b>"; html += System.Web.HttpUtility.HtmlEncode(comment); html += "</b>."; return html;}

Proxy working mechanism:

Ajax. PageHandlerFactory is used to obtain the details of functions with custom attributes through reflection. Handler looks for functions with custom attributes of AjaxMethod, obtains their features (return type, name, parameters), and creates client proxies based on the information. Specifically, ajax creates a JavaScript Object of the same type as the server function as a proxy.

Ajax technology can provide a rich client experience, while ajax.net provides the possibility for you to easily implement such powerful functions. You can view the latest ajax.net documents through the following link:

Keep a close eye on the AJAX. Net wrapper website: http://ajax.schwarz-interactive.de/

For a good hands-on sample, check out the following demo application: http://ajax.schwarz-interactive.de/download/ajaxsample.zip

Reference ①: http://www.cnblogs.com/U2USoft/articles/332439.html

Reference link ②: http://www.jb51.net/article/42176.htm

Related Article

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.