Ajax learning notes --- Three Ajax implementation methods [recommended], ajax --- 3
Ajax: Asynchronous JavaScript and Xml, Asynchronous js scripts and xml, which are often used to implement partial Asynchronous page refresh, which is of great help to improve user experience. xml is advantageous in multiple languages, but Ajax uses Json objects rather than Xml to process data.
(1) Ajax history... understanding knowledge
Ajax belongs to Web Front-end development technology and is closely related to javascript exceptions. ajax is a new technology that implements asynchronous communication without refreshing, and this technology can be implemented in many ways. netScape, the originator of the browser, first invented the LiveScript script language to enrich the forms of web elements, so that web pages can present dynamic results. after subsequent revisions and upgrades, the JavaScript language was born. In the same period, Microsoft also saw the prospect of the Internet and began to get involved in the Internet industry and launched the JScript Language, it is a pity that JavaScript is not mature and development lags behind. microsoft's determination to the Internet eventually led to MS's long and tortuous acquisition history of NS.
The Dynamic HTML Language (Dynamic Hyper Text Markup Language) is to place javascript in the element node of the Dom tree to provide Dynamic display behavior for elements.
(2) Two ideas for Web Front-end development:A. JavaScript + XHR + CSS B. Flash ---> browser plug-in ---> Flex (Adobe); Silverlight4.0 (MS)
1. Ajax: Taking XHR (XMLHttpRequest) of MS as the core ---> Ajax
2. flash: MicroMedia ---> acquired by Adobe ---> flex (a combination of technologies such as ActionScript and Rich Internet Application)
3. SilverLight: SilverLight launched by Microsoft to compete with flex
Note:
In order to be able to communicate asynchronously with the server in the background, Microsoft added two components in IE: The component responsible for communicating with the server (XMLHTTPRequest) and the XML processing component. XML is used as the carrier of data exchange. xml is advantageous in multi-language processing, but XML processing costs are high. In fact, Ajax usually uses Json objects to transmit data between Client browsers and servers.
The webpage generation process is actually completed by a group of programs on the server. In this way, data is transmitted in the JS language of the client and the C # language of the server ,. net provides Json serialization and deserialization devices to provide conversion between the C # And Json objects on the server side. on the browser side, you can use the eval () function to obtain the Json string passed by the server and convert it into a Json object.
(3) What issues does Ajax solve?
We all know that when the client requests a page from the server, the server first dynamically calculates and generates the page, and then sends it to the client. The client browser compiles and presents the page in sequence.
If there is no Ajax: if there is a user verification control on the page, when the client browser displays the user verification control, it will wait for the server's verification results to continue to render the page elements after receiving the results. this verification process usually requires database reading and other operations. This is the so-called synchronous method. in this way, the webpage may be displayed in a false state.
After Ajax is used: it is also a verification control. After the client submits the verification request, it continues to present other elements in sequence. after the verification result is obtained, javascript modifies the DOM object in the memory on the client and presents it to the user (Note: Only the DOM object in the memory is modified here, the page file received by the client is not modified ). in this way, the asynchronous mode will not be suspended, and the client also saves time overhead when waiting for the server to return results.
(4) Ajax implementation(The implementation of Ajax in Section 3 should be noted that the effects of Ajax can be achieved through WebService .)
1. asynchronous Ajax call in Js:. new B. onreadystatechange (processing responseText) c. open (get and post) d. send (synchronous call:. new B. open (get and post) c. send d. responseText)
// Ajax.html
<! 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> <title> Ajax of Javascript & jQuery </title>
Then, you need to add a general processing program similar to json. ashx in the project to provide relevant data (for example, drawing a table calendar and performing database verification)
// Json. ashx
<% @ WebHandler Language = "C #" Class = "Json" %> using System; using System. web; publicclass Json: IHttpHandler {publicvoid ProcessRequest (HttpContext context) {context. response. contentType = "text/plain"; // for static content, you must disable the browser cache; otherwise, the old result is always context. response. cache. setCacheability (HttpCacheability. noCache); string name = "Mike"; string jsonFormat = "{\" name \ ": \" {0 }\"}}"; // {,} is a special escape character string Json = string to avoid conflicts with {In json. format (jsonFormat, name); context. response. output. write (json);} publicbool IsReusable {get {returnfalse ;}}}
// Jquery. ashx
<%@ WebHandler Language="C#" Class="jquery"%>using System;using System.Web;publicclass jquery : IHttpHandler {publicvoid ProcessRequest (HttpContext context) {context.Response.ContentType ="text/plain";context.Response.Cache.SetCacheability(HttpCacheability.NoCache);DateTime now = DateTime.Now;string jqueryFormat ="<span>{0}</span>";string jquery =string.Format(jqueryFormat, now);context.Response.Write(jquery);}publicbool IsReusable {get {returnfalse;}}}
2.1 use AjaxPro2:
A. add AjaxPro2 class library (AjaxPro2.dll) B. add the configuration file c. create a class library file (cs file) in App_Code to provide Ajax service, and register Ajax (Page_Load event) d in the background cs file corresponding to the page. in the class library file (cs file) in App_Code, compile the processing method with Ajax labels. e. use the script to process the result (modify the DOM object in memory) in the aspx file at the front end and display it on the page.
// Add a configuration file in B. webconfig
<location path="ajaxpro"><system.web>
// C. Create a class library file (cs file) in App_Code to provide the Ajax service, and register Ajax (Page_Load event) in the background cs file corresponding to the page)
// Default. aspx. cs File
Protectedvoid Page_Load (object sender, EventArgs e) {AjaxPro. Utility. RegisterTypeForAjax (typeof (CalendarServices); // AjaxPro automatically generates a script based on the registered type}
// D. Compile the processing method with Ajax labels in the class library file (cs file) in App_Code
// CalendarServices. cs
Using System; using System. collections. generic; using System. linq; using System. web; publicclass CalendarServices {[AjaxPro. ajaxMethod] publicbool save (string date, string tile, string detail) {System. threading. thread. sleep (5000); // used to test asynchronous returntrue; // This is simple and returns true directly }}
// E. Use the script to process the result (modify the DOM object in memory) in the aspx file at the front end and display it on the page.
// Default. aspx File
<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default. aspx. cs" Inherits = "_ 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>
2.2. previously Used boss Ajax (the maintenance of old projects may be used, in fact, very similar to 2nd):. reference Ajax framework class library B. add configuration c. add the Ajax service class to App_Code, and register Ajax (Page_Load event) d in the CS file. processing Method e. method f. JS Processing Method
// A. reference the Ajax framework class library Ajax. dll
// B. webconfig add Configuration
// C. Register Ajax in the CS file (Page_Load event)
Ajax. Utility. RegisterTypeForAjax (typeof (SysBase_UserEdit); // SysBase_UserEdit is the name of the page file.
// D. How to Deal with the Ajax tag in the CS file in App_Code
[Ajax.AjaxMethod]public DataSet getRoleData(int Roleid){DataSet ds =new DataSet();ds = r.SelectRoleData(string.Format(" and id={0}", Roleid));return ds;}
// Method for triggering JS by binding e. Button
This. DDLRole. attributes. add ("onpropertychange", "onCommandInputPropertyChange ();"); // Add the Attribute-based button binding method in the Page_Load event manually in the aspx file.
// F. JS Processing Method
<Script> function onCommandInputPropertyChange () {if (event. propertyName = "value") {var cmdInput = event. srcElement; if (cmdInput. value! = 0) {// alert (cmdInput. value); BindRoleName (cmdInput. value) ;}}// bind the role name function BindRoleName (RoleID) {// SysBase_UserEdit is the name of the aspx page SysBase_UserEdit.getRoleData (RoleID, get_AllName);} function get_AllName (response) {var AllName = document. getElementById ("DDLAjax"); AllName. length = 0; if (response. value! = Null) {var ds = response. value; if (ds! = Null & typeof (ds) = "object") {var name = ds. tables [0]. rows [0]. rolename; var id = ds. tables [0]. rows [0]. id; AllName. options. add (new Option (name, id) ;}}</script>
3. VS2008 integrated Ajax:
A. install the plug-in (Microsoft ASP. NET 2.0 AJAX Extensions) B. place the ScriptManager control next to the Form Element c. use UpdatePanel and ContentTemplate to package at the beginning of the table element to be refreshed. place the trigger Element Between ContenTemplate and UpdatePanel at the end of the table element, and register the Ajax trigger button e. reference class library Ajax2 f. webConfig needs to be configured in VS2005
// D. Place the trigger Element Between ContenTemplate and UpdatePanel at the end of the table element and register the Ajax trigger button (btn_Search and btn_Delete are buttons)
<Triggers><asp:AsyncPostBackTrigger ControlID="AspNetPager1"/><asp:AsyncPostBackTrigger ControlID="btn_Search"/><asp:AsyncPostBackTrigger ControlID="btn_Delete"/></Triggers>
// F. VS2005 requires webConfig Configuration
<HttpHandlers> <! -- Call AjaxPro.2 --> <add verb = "POST, GET" path = "ajaxpro /*. ashx "type =" AjaxPro. ajaxHandlerFactory, AjaxPro.2 "/> <remove verb =" * "path = "*. asmx "/> <add verb =" * "path = "*. asmx "validate =" false "type =" System. web. script. services. scriptHandlerFactory, System. web. extensions, Version = 1.0.61025.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35 "/> <add verb =" * "path =" * _ AppService. axd "validate =" false "type =" System. web. script. services. scriptHandlerFactory, System. web. extensions, Version = 1.0.61025.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35 "/> <add verb =" GET, HEAD "path =" ScriptResource. axd "type =" System. web. handlers. scriptResourceHandler, System. web. extensions, Version = 1.0.61025.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35 "validate =" false "/>
==================================================================== ========================
About the first one: Ajax asynchronous calls in Js, add something to the topic.
About parameter transfer:
1.
Parameters are stored in the URL. For example:
Xhr. open ("get", "json. ashx? Name = xxx ", true );
Xhr. send (null );
On the server side (json. ashx background Code), which can be obtained by using the context parameter object of the HttpContext type. request. queryString ["name"]... wait (you can view it in the debugging status)
2.
Parameters are stored in the request package Body. For example:
Xhr. open ("post", "json. ashx", true );
Xhr. send ("xxx ");
Or
Xhr. send ("name = xxx ");
The corresponding server side (json. ashx background Code) has two methods for obtaining "non-key-value pairs" and "key-value pairs" in 2:
Non-key-value pairs: obtained using context. Request. InputStream, for example:
System. IO. Stream stream = context. Request. InputStream;
System. IO. StreamReader sr = new System. IO. StreamReader (stream );
String strParam = sr. ReadToEnd ();
If encoding conversion is involved, you can adjust it yourself.
Key-Value Pair: Use context. Request. Form ["name"]... to obtain
The above Ajax Study Notes-the three Ajax implementation methods [recommended] are all the content shared by Alibaba Cloud xiaobian. I hope you can give us a reference and support for the customer's home.