This time I will bring you 3 ways to implement ajax. What are the precautions for implementing ajax? Here are practical cases, let’s take a look.
Ajax: Asynchronous JavaScript and Json objects are often used instead of It belongs to Web front-end development technology and has an extremely close connection with JavaScript. Ajax is a technology that realizes asynchronous communication without refreshing, and this technology can be implemented in many ways. It was first invented by NetScape, the originator of the browser. The LiveScript scripting language was used to enrich the expression of web page elements and enable the web page to present dynamic effects. After subsequent revisions and upgrades, the JavaScript language was born. At the same time, Microsoft also saw the prospects of the Internet and began to He got involved in the Internet industry and launched the JScript language. Unfortunately, it was not as mature as JavaScript and its development was sluggish. In the end, Microsoft's determination for the Internet contributed to MS's long and tortuous acquisition of NS.
Let me mention it here, Dynamic Hyper Text Markup Language is to place javascript in the element node of the Dom tree to provide dynamic display behavior for the elements. (2) Two aspects of Web front-end development Idea:
a. JavaScript + XHR + CSS b. Flash ---> Browser plug-in ---> Flex(Adobe); Silverlight4.0(MS)
1. Ajax: Taking MS's XHR (XMLHttpRequest) as the core ---> Ajax
2. flash: MicroMedia ---> Acquired by Adobe ---> flex (covers ActionScript and Rich Internet Application A combination of other technologies)3. SilverLight: SilverLight launched by Microsoft to compete with flex
Note:
In order to be able to communicate with the server asynchronously in the background For communication, Microsoft added two components to IE: the component responsible for communicating with the server (XMLHTTPRequest) and the XML processing component. Using XML as the carrier of data exchange has advantages in multi-language processing, but the processing cost of XML is relatively high. High, in fact, Json objects are usually used in Ajax to transfer data between the client browser and the server.
The generation process of web pages is actually completed by a set of programs on the server, so that in order to To transfer data between JS language and server-side C# language, .Net provides
Json serialization
and deserializer to provide conversion between server-side C# objects and Json objects. It can be used on the browser side The eval() function obtains the Json string passed by the server and converts it into a Json object.
(3) What problems does Ajax solve
We all know , 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 renders the page sequentially.
Without Ajax: If If the page has a user verification control, then when the client browser presents the user verification control, it will wait for the server's verification result. After receiving the result, it can continue to present the page elements. This verification process usually requires operations such as reading the database. This is the so-called synchronization method. This method will cause the web page to appear in a state of suspended animation.After using Ajax: It is also a verification control. After the client submits the verification request, it will continue to present other elements in sequence. . After the verification result is obtained, the DOM object in the memory is modified by javascript on the client side and presented to the user (note: only the DOM object in the memory is modified here, and the page file received by the client is not modified). In this way, Using the asynchronous method, there will be no suspended animation state, and the client also saves the time spent waiting for the server to return results.
(四)Ajax implementation
(The implementation of Ajax in 3, it should be noted that: the effects that Ajax can achieve can be achieved through WebService.)
1. Ajax asynchronous call in Js: a.new b.onreadystatechange (processing responseText) c.open (get mode and post mode) d.send (synchronous call: a.new b.open (get mode and post mode) c.send d.responseText)
//ajax.html
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | <!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>
</head>
<body>
<a href= "javascript:getData();" >Javascript-Ajax: Click me</a><br />
<br />
<br />
<input id= "btn" type= "button" value= "jQuery-Ajax: Clike me" />
<hr />
<p id= "show" >
</p>
<script type= "text/javascript" >
function getData() {
var xhr;
if (window.ActiveXObject) {
xhr = new ActiveXObject( "Microsoft.XMLHTTP" );
}
elseif (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
thrownew Error( "Ajax is not supported by this browser" );
}
var elem = document.getElementById( "show" );
xhr.onreadystatechange = function () {
if (xhr.readyState ==4) {
if (xhr.status ==200) {
var json = xhr.responseText;
var obj = eval ( "(" + json + ")" );
elem.innerHTML = "<span>" + obj.name + "</span>" ;
}
}
}
xhr.open( "get" , "json.ashx" , true);
xhr.send(null);
}
</script>
<script src= "jquery-1.4.2.js" type= "text/javascript" ></script>
<script type= "text/javascript" >
$( function () {
$( "#btn" ).click( function showData() {
$( "#show" ).load( "jquery.ashx" );
});
});
</script>
</body>
</html>
|
Copy after login
Then you also need to add a general handler similar to json.ashx in the project to provide relevant data (such as drawing table calendars, database verification, etc.)
//json. ashx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <%@ WebHandler Language= "C#" Class= "Json" %>
using System;
using System.Web;
publicclass Json : IHttpHandler {
publicvoid ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain" ;
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
string name = "Mike" ;
string jsonFormat = "{{ \"name\": \"{0}\" }}" ;
string json =string.Format(jsonFormat, name);
context.Response.Output.Write(json);
}
publicbool IsReusable {
get {
returnfalse;
}
}
}
|
Copy after login
//jquery.ashx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <%@ 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;
}
}
}
|
Copy after login
2.1 Using AjaxPro2:
a. Add AjaxPro2 class library (AjaxPro2.dll) b. Add configuration in webconfig File c. Create class library file (cs file) in App_Code to provide Ajax service, and register Ajax in the background cs file corresponding to the page (in the Page_Load event) d. Class in App_Code The library file (in the cs file) writes the processing method with the Ajax tag e. Use the script in the aspx file in the foreground to process the results (modify the DOM object in the memory) and display it on the page
//b. Add configuration file in webconfig
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <location path= "ajaxpro" >
<system.web>
<httpHandlers>
<add verb= "*" path= "*.ashx" type= "AjaxPro.AjaxHandlerFactory,AjaxPro.2" />
</httpHandlers>
<!--
If you need to have Ajax.NET Professional methods running on the
login page you may have to enable your own authorization configuration
here.
-->
<!--
<authorization>
<deny users= "?" />
</authorization>
-->
</system.web>
</location>
|
Copy after login
//c. Create a class library file (cs file) in App_Code to provide Ajax service, and register Ajax in the background cs file corresponding to the page (in the Page_Load event)
//default.aspx.cs file
1 2 3 4 | protectedvoid Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(CalendarServices));
}
|
Copy after login
//d. Write a processing method with Ajax tag in the class library file (cs file) in App_Code
//CalendarServices.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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);
returntrue;
}
}
|
Copy after login
//e. Use script in the aspx file in the foreground to process the results (modify the DOM object in memory) and display it on the page
//default. aspx file
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 27 28 29 30 31 32 33 34 35 36 37 38 39 | <%@ 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></title>
</head>
<body>
<form id= "form1" runat= "server" >
<p>
日期:<input id= "date" type= "text" /><br />
标题:<input id= "title" type= "text" /><br />
详情:<textarea id= "detail" cols= "80" rows= "5" ></textarea>
<hr />
<input id= "btn" type= "button" value= "确定" />
</p>
<p>
<script src= "jquery-1.4.2.js" type= "text/javascript" ></script>
<script type= "text/javascript" >
$( function () {
$( "#btn" ).click( function () {
var date = $( "#date" ).val();
var title = $( "#title" ).val();
var detail = $( "#detail" ).val();
CalendarServices.save( date , title, detail, function (result) {
if (result.error !=null) {
alert(result.error.Message);
}
if (result.value) {
alert( "服务器返回true! " );
}
});
});
});
</script>
</p>
</form>
</body>
</html>
|
Copy after login
2.2. Boss Ajax used before (may be used to maintain old projects, in fact it is very similar to the second type): a. Reference the Ajax framework class library b. Add configuration in webconfig c. In App_Code Add the Ajax service class in the CS file and register Ajax in the CS file (in the Page_Load event) d. The processing method with the Ajax tag in the CS file in App_Code e. The button binding triggers the JS method f. The JS processing method
//a. Reference the class library Ajax.dll of the Ajax framework
//b. Add configuration to webconfig
1 2 3 | <httpHandlers>
<add verb= "POST,GET" path= "ajax/*.ashx" type= "Ajax.PageHandlerFactory, Ajax" />
</httpHandlers>
|
Copy after login
//c. Register Ajax in the CS file (in the Page_Load event )
1 | Ajax.Utility.RegisterTypeForAjax(typeof(SysBase_UserEdit));
|
Copy after login
//d. Processing method with Ajax tag in CS file in App_Code
1 2 3 4 5 6 7 | [Ajax.AjaxMethod]
public DataSet getRoleData(int Roleid)
{
DataSet ds = new DataSet();
ds = r.SelectRoleData(string.Format( " and id={0}" , Roleid));
return ds;
}
|
Copy after login
//e. Method for triggering JS by button binding
1 | this.DDLRole.Attributes.Add( "onpropertychange" , "onCommandInputPropertyChange();" );
|
Copy after login
//f. JS processing method
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 27 28 | <script>
function onCommandInputPropertyChange(){
if (event.propertyName == "value" ){
var cmdInput = event.srcElement;
if (cmdInput.value != 0){
BindRoleName(cmdInput.value);
}
}
}
function BindRoleName(RoleID){
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>
|
Copy after login
3. VS2008 integrated Ajax:
a. For VS2005, you need to install the plug-in (Microsoft ASP.NET 2.0 AJAX Extensions) b. Next to the Form element Place the ScriptManager control c. At the first position of the table element to be refreshed, wrap it with UpdatePanel and ContentTemplate d. Place the trigger element between ContentTemplate and UpdatePanel at the end of the table element, and register the Ajax trigger button e. Reference the class library Ajax2 f.VS2005 Need to configure webConfig
//d. Place trigger element between ContentTemplate and UpdatePanel at the end of table element, register Ajax trigger button (btn_Search, btn_Delete are buttons)
1 2 3 4 5 | <Triggers>
<asp:AsyncPostBackTrigger ControlID= "AspNetPager1" />
<asp:AsyncPostBackTrigger ControlID= "btn_Search" />
<asp:AsyncPostBackTrigger ControlID= "btn_Delete" />
</Triggers>
|
Copy after login
//f . VS2005 needs to configure webConfig
1 2 3 4 5 6 7 8 | <httpHandlers>
<!-- 调用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" />
</httpHandlers>
|
Copy after login
============================ dividing line======== ====================
Regarding the first type: Ajax asynchronous call in Js, I will add some stuff and won’t start it separately
About parameter passing:
1.
Pass parameters in get mode, and the 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), you can use HttpContext Type parameter object context to obtain, the acquisition method is context.Request.QueryString["name"]....etc. (see it in debugging state)
2.
Pass parameters in post method, The parameters are stored in the body of the request package, for example:
xhr.open("post","json.ashx",true);
xhr.send("xxx");
or
xhr.send("name=xxx");
Corresponding server side (json.ashx background code), for "non-key-value pairs" and " in 2 There are two ways to obtain key-value pairs:
Non-key-value pairs: Use context.Request.InputStream to obtain them, such as:
1 2 3 | System.IO.Stream stream = context.Request.InputStream;
System.IO.StreamReader sr = new System.IO.StreamReader(stream);
string strParam = sr.ReadToEnd();
|
Copy after login
If it involves encoding conversion, you will need to adjust it yourself.
Key-value pair: Use context.Request.Form["name"]... to get
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other php Chinese websites related articles!
Recommended reading:
How to prevent the ajax callback from being intercepted by the browser when opening a new form
jQuery+AJAX calls the background of the page
The above is the detailed content of 3 ways to implement ajax. For more information, please follow other related articles on the PHP Chinese website!