Home  >  Article  >  Web Front-end  >  3 ways to implement ajax

3 ways to implement ajax

php中世界最好的语言
php中世界最好的语言Original
2018-04-04 15:57:222491browse

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

b585974ae3b7dba3039af53a9593f9c4
383eb734b02b508089ba2d78eb4c6f68
93f0f5c25f18dab9d176bd4f6de5d30e
b2386ffb911b14667cb8f0f91ea547a7Ajax of Javascript & jQuery6e916e0f7d1e588d4f442bf645aedb2f
9c3bca370b5104690d9ef395f2c5f8d1
6c04bd5ca3fcae76e30b72ad730ca86d
a4944a33d466fdeb777db7c0cddde24aJavascript-Ajax: Click me5db79b134e9f6b82c0b36e0489ee08edff9d32c555bb1d9133a29eb4371c1213
ff9d32c555bb1d9133a29eb4371c1213
ff9d32c555bb1d9133a29eb4371c1213
ff5f8a68d680bdab4d70addeeb2a1b4f
cdcaaee4c9b94464012808ae8e1b67a4
8000ba296d549aa85ddd602dfed0879b
94b3e26ee717c64999d7867364b1b4a3
8019067d09615e43c7904885b5246f0a
function getData() {
//创建XMLHttpRequest通信对象
var xhr;
if (window.ActiveXObject) { //标准情况下, 只能有两个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"); //用来显示处理结果
//使用onreadystatechange事件处理结果
xhr.onreadystatechange =function() {
if (xhr.readyState ==4) { // readyState表示服务器响应状态. 4: 响应接收完毕
if (xhr.status ==200) { // status 表示 http 请求的状态
var json = xhr.responseText; //从请求中回应中获得json串
var obj = eval("("+ json +")"); // 借助 eval 将 json 串转化为对象, 在客户端浏览器必须解析为js对象
elem.innerHTML ="45a2772a6b6107b401db3c9b82c049c2"+ obj.name +"54bdf357c58b8a65c66d7c19c8e4d114";
}
}
}
//通过open设置请求方式
xhr.open("get", "json.ashx", true); //默认为ture, false表示同步方式
//发送请求
xhr.send(null);
/* 同步方式, false表示不适用异步方式
xhr.open("get", "json.ashx", false);
xhr.send(null);
//处理结果
alert(xhr.responseText);
*/
}
2cacc6d41bbb37262a98f745aa00fbf0
75e04825979975331ecfa2ba27e4aa262cacc6d41bbb37262a98f745aa00fbf0
8019067d09615e43c7904885b5246f0a
$(function() { //ready函数, 脚本加载完即执行, 也可以用$(...$("#btn").click...)();加载
$("#btn").click(function showData() { //按钮上添加onclick事件, 事件处理方法为showData()
$("#show").load("jquery.ashx"); //从jquery.ashx中获取数据元素(innerHTML的内容), 并显示在p中
});
});
2cacc6d41bbb37262a98f745aa00fbf0
36cc49f0c466276486e50c850b7e4956
73a6ac4ed44ffec12cee46588e518a5e

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

c7ff4b40161fd6c8a00dc7690f832b91
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}\" }}"; //{{、}}是为了避免和Json中的{冲突而采用的特殊转义符
string json =string.Format(jsonFormat, name);
context.Response.Output.Write(json);
}
publicbool IsReusable {
get {
returnfalse;
}
}
}

//jquery.ashx

fecdf968e6bdaa0184e3cc74e96e4509
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 ="45a2772a6b6107b401db3c9b82c049c2{0}54bdf357c58b8a65c66d7c19c8e4d114";
string jquery =string.Format(jqueryFormat, now);
context.Response.Write(jquery);
}
publicbool IsReusable {
get {
returnfalse;
}
}
}

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

7448052ee0aa438ce73e0a8b3dd611ad
2dc15ec6bc814c3aa45b55d017848bed
7342c004d9ee91801ac5c2892c1ed716
d77b1e247b97cf6a9c1fdda6c7a23d67
a678e556e2e40b2e2d09f69cb325521e
eb1e6c2aa0bb52bd43b314e30abaced1
0baa241499d00b9f72989b26007af186
b525c13248727c3ef0eae09176cb9d65
137d563e8590cea2318915a677e376a3
-->
4ec4537ca3582453b3a7c44816bcf480
eb393cd7f0c41cf1136847ec1779eae4

//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

protectedvoid Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(CalendarServices)); //AjaxPro会根据注册的类型自动生成脚本
}
//d. Write a processing method with Ajax tag 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); //用来测试异步
returntrue; //这里为简单, 直接返回true
}
}
//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

3e93250a76b57894af92dc400b183f5e
b585974ae3b7dba3039af53a9593f9c4
383eb734b02b508089ba2d78eb4c6f68
22e6244c9f89e2a72231546ed5a2733f
b2386ffb911b14667cb8f0f91ea547a76e916e0f7d1e588d4f442bf645aedb2f
9c3bca370b5104690d9ef395f2c5f8d1
6c04bd5ca3fcae76e30b72ad730ca86d
a56165225b53ae2239a99091f5fba8ce
e388a4556c0f65e1904146cc1a846bee
日期:09e49708bcedb0348acbe74892c4d650ff9d32c555bb1d9133a29eb4371c1213
标题:0011a500b134bfab6059b11b2ac1a083ff9d32c555bb1d9133a29eb4371c1213
详情:4850dc40fe676b0981b4bf5d42d7938140587128eee8df8f03d0b607fe983014
cdcaaee4c9b94464012808ae8e1b67a4
062cbd68642114d29cfacc632d9cc1ca
94b3e26ee717c64999d7867364b1b4a3
e388a4556c0f65e1904146cc1a846bee
75e04825979975331ecfa2ba27e4aa262cacc6d41bbb37262a98f745aa00fbf0
8019067d09615e43c7904885b5246f0a
$(function() {
$("#btn").click(function() {
var date = $("#date").val();
var title = $("#title").val();
var detail = $("#detail").val();
//由AjaxPro生成的js代理, 很像C#中类库的使用, 其中function(result)是异步的结果处理方法
CalendarServices.save(date, title, detail, function(result) {
if (result.error !=null) { //服务器上出现异常
alert(result.error.Message);
}
if (result.value) { //服务器cs文件中的方法返回永真
alert("服务器返回true! ");
}
});
});
});
2cacc6d41bbb37262a98f745aa00fbf0
94b3e26ee717c64999d7867364b1b4a3
f5a47148e367a6035fd7a2faa965022e
36cc49f0c466276486e50c850b7e4956
73a6ac4ed44ffec12cee46588e518a5e
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

7342c004d9ee91801ac5c2892c1ed716
818d942dd69335e976415bd974d8f403
a678e556e2e40b2e2d09f69cb325521e
//c. Register Ajax in the CS file (in the Page_Load event )

Ajax.Utility.RegisterTypeForAjax(typeof(SysBase_UserEdit)); //SysBase_UserEdit是页面文件名称
//d. Processing method with Ajax tag in 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;
}
//e. Method for triggering JS by button binding

this.DDLRole.Attributes.Add("onpropertychange", "onCommandInputPropertyChange();"); //在Page_Load事件中基于Attribute为按钮绑定方法, 在aspx文件中手动添加也可以
//f. JS processing method

3f1c4e4b6b16bbbd69b2ee476dc4f83a 
  function onCommandInputPropertyChange(){ 
    if (event.propertyName == "value"){ 
      var cmdInput = event.srcElement; 
      if (cmdInput.value != 0){ 
        //alert(cmdInput.value); 
    BindRoleName(cmdInput.value);    
      } 
    } 
  } 
  //绑定角色名 
  function BindRoleName(RoleID){ 
  //SysBase_UserEdit是aspx页面的名称 
    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)); 
    } 
  } 
  } 
2cacc6d41bbb37262a98f745aa00fbf0
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)

0a8ecf1acd1a0a3f90f72a96b90e798e
b2d86b00b6244ca94e110698e939eca6
60fb8f191e5eb174b120bfd153c6c543
45e7fb75d0c052202c651a994d0d92fa
964d468c0797735e3eb6033b3b17750b
//f . VS2005 needs to configure webConfig

7342c004d9ee91801ac5c2892c1ed716
33f009ceb7c4b8445d06b6373519952d
87366aed792f07ec516ac37f05d956f5
d343374be96a9d7554af644c494a8647
994024a0a6f3fd08208ef5cc0c126461
4cb54fd5f1591ce0177321bcb07d1670
44b23a7d49d2f9b59bfdb74d9fbb1604
a678e556e2e40b2e2d09f69cb325521e
============================ 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:

System.IO.Stream stream = context.Request.InputStream;
System.IO.StreamReader sr = new System.IO.StreamReader(stream);
string strParam = sr.ReadToEnd();

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn