Ajax Learning Notes---3 AJAX implementation Methods "recommended" _ajax related

Source: Internet
Author: User

Ajax:asynchronous JavaScript and XML, asynchronous JS scripts and XML, commonly used to implement the local asynchronous refresh of the page, to improve the user experience is a great help. XML has an advantage in multiple languages, but Ajax technology actually uses JSON objects rather than XML to process data.

(i) Ajax history .... Understanding Sexual knowledge

Ajax belongs to the Web front-end development technology, and JavaScript has an unusually close connection. Ajax is a technology that realizes asynchronous communication without refreshing, and this technology can be implemented in many ways. The originator of the browser Netscape (Netscape) first invented the LiveScript scripting language, to enrich the form of Web page elements, so that the Web page can show dynamic effects. After the subsequent revisions to the birth of the JavaScript language, Microsoft (Microsoft) Company also saw the prospects of the Internet, began to dabble in the Internet industry, launched a JScript language, unfortunately no JavaScript mature, development retardation. Ultimately, Microsoft's commitment to the Internet has contributed to the long, tortuous process of MS's acquisition of the NS.

In this case, the Dynamic HTML language (dynamically Hyper Text Markup Language) is where JavaScript is placed in the element nodes of the DOM tree, providing dynamic display behavior for the elements.

(ii) Web front-end development of two ideas: A. JavaScript + XHR + CSS B. Flash---> Browser plugins---> Flex (Adobe); Silverlight4.0 (MS)

1. Ajax: With Ms Xhr (XMLHttpRequest) as the core---> Ajax

2. Flash:micromedia---> was acquired by Adobe---> Flex (which covers the combination of ActionScript and rich Internet application technologies)

3. Silverlight: The Silverlight launched by Microsoft to counter Flex

Note:

In order to be able to communicate asynchronously with the server in the background, Microsoft added two components to IE: the component responsible for communicating with the server (XMLHttpRequest) and the processing component of the XML. Using XML as the carrier of data exchange has advantages in multi-language processing, but the processing cost of XML is high, in fact, the JSON object is usually used in Ajax to pass data between client browser and server.

The process of building a Web page is actually done by a set of programs on the server, so that data can be passed in the client's JS language and the server-side C # language. NET provides JSON serialization and deserialization to provide conversions between server-side C # objects and JSON objects. On the browser side, you can use the Eval () function to get the JSON string passed over by the server into the JSON object.

Three What problems does Ajax solve

As we all know, when a client requests a page from a server, the server first dynamically calculates and generates the page, and then sends it to the client. The client browser compiles and renders the page sequentially.

In the absence of Ajax: If the page has a user validation control, then when the client browser renders the user validation control, it waits for the server to validate the results before continuing to render the page elements. This validation process is usually done by reading the database and so on, which is called the synchronization method. And this way, will cause the Web page to appear the suspended animation state.

After using Ajax: The same is the validation control, the client submits the validation request and continues to render the other elements sequentially. When the validation results are obtained, JavaScript modifies the in-memory DOM object after the client and presents it to the user (note: This modifies only the DOM object in memory and the paging file received by the client is not modified). Thus, in an asynchronous manner, there is no suspended animation, and the client also saves the time it costs to wait for the server to return results.

(iv) implementation of Ajax (3 in the implementation of Ajax, need to explain: Ajax can achieve the effect, through the webservice can be achieved.)

1. JS Ajax Asynchronous Call: A.new b.onreadystatechange (processing responsetext) C.open (Get mode and post method) D.send (synchronous call: A.new B.open (Get Way and PO St mode) 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 ">  

Then you will also need to add a generic handler similar to the JSON.ASHX in your project to provide relevant data (such as: Table Calendar drawing, database validation, etc.)

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, browser caching needs to be disabled, otherwise the old result context is always used
. Response.Cache.SetCacheability (Httpcacheability.nocache);

String name = "Mike";

String Jsonformat = "{{\" name\ ": \" {0}\ "}}"; {{,}} is a special escape character string JSON =string that is used to avoid conflicts 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 a configuration file in the AjaxPro2 class library (AjaxPro2.dll) b.webconfig Create a class library file (cs file) in App_Code to provide AJAX services and register Ajax in the corresponding background CS file in the page (Page_ Load Event D. Write a processing method with Ajax tags in the class library file (cs file) in App_Code E. Use script processing results in the ASPX file in the foreground (Modify the DOM object in memory) and display on the page

Add configuration file in B.webconfig

<location path= "Ajaxpro" >
<system.web>
here.
-->
<!--
<authorization>
<deny users= "?" />
</authorization>
-->
</system.web>
</location>

C. Create a class library file (cs file) in App_Code to provide AJAX services and register Ajax in the corresponding background CS file in the page (Page_Load event)

Default.aspx.cs file

protectedvoid Page_Load (object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax ( calendarservices)); Ajaxpro will automatically generate scripts based on registered types
}

D. Writing a processing method with Ajax tags in a 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;//Here for simplicity, direct return True
}
}

E. Use script processing results in foreground ASPX files (modify in-memory DOM objects) and display 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 ">  

2.2. Previous use of the Boss Ajax (maintenance of old items may be used, in fact, similar to the 2nd): A. Referencing the Ajax framework class library B. Webconfig add a configuration C. Add an AJAX service class to the App_Code and register Ajax in the CS file (Page_ Load event D. Processing methods with AJAX tags in cs files in App_Code E. The method of Trigger JS by button binding F.js processing method

A. Class libraries referencing the AJAX framework Ajax.dll

B. Webconfig Add configuration

 
 

C. Register Ajax in CS file (Page_Load event)

Ajax.Utility.RegisterTypeForAjax (typeof (Sysbase_useredit)); Sysbase_useredit is the paging file name

D. Processing methods with Ajax tags in cs files 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;
}

E. Button binding to Trigger JS method

This. DDLROLE.ATTRIBUTES.ADD ("Onpropertychange", "Oncommandinputpropertychange ();"); In the Page_Load event, the button binding method is based on attribute, which can be added 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); 
  }} Binding 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.vs2005 you need to install the plugin (Microsoft asp.net 2.0 AJAX Extensions) b. Place the ScriptManager control C next to the form element. At the top of the table element you want to refresh, Wrap it up with UpdatePanel and ContentTemplate D. Place the trigger element between Contentemplate and UpdatePanel at the end of the table element, registering the Ajax trigger button E. Reference class library Ajax2 F. VS2005 need to configure Webconfig

D. Place the trigger element between Contentemplate and UpdatePanel at the end of the table element, registering the Ajax trigger button (Btn_search, btn_delete all buttons)

<Triggers>
<asp:asyncpostbacktrigger controlid= "AspNetPager1"/>
<asp: Asyncpostbacktrigger controlid= "Btn_search"/> <asp:asyncpostbacktrigger controlid= "Btn_Delete
"/>
</Triggers>

F. VS2005 need to configure Webconfig


 

============================ Split Line ============================

About the first: JS in the Ajax asynchronous call, add something, not a separate opening

About parameter passing:

1.
Get mode arguments, which are stored in the URL, for example:

Xhr.open ("Get", "json.ashx?name=xxx", true);
Xhr.send (NULL);

In the server (JSON.ASHX code), you can use the HttpContext type of parameter object context to get the way context. request.querystring["Name"] .... Et cetera (see yourself in the Debug state)

2.
Post method, parameters are saved in the package body of the request package, for example:

Xhr.open ("Post", "Json.ashx", true);
Xhr.send ("xxx");

Or
Xhr.send ("name=xxx");

The corresponding server side (JSON.ASHX code), for 2 "Non-key pairs", "key value pair" has two ways to get:

Non-key value pairs: use context. Request.inputstream access, such as:

System.IO.Stream Stream = context. Request.inputstream;
System.IO.StreamReader sr = new System.IO.StreamReader (stream);
String strparam = Sr. ReadToEnd ();

Which involves coding the conversion of itself under adjustment.

Key value pairs: use context. request.form["Name"] ... Get

The above Ajax learning notes---3 kinds of AJAX implementation method "Recommendation" is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

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.