Home Web Front-end JS Tutorial 3 ways to implement ajax

3 ways to implement ajax

Apr 04, 2018 pm 03:57 PM
ajax accomplish method

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

<!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() {
//创建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 ="<span>"+ obj.name +"</span>";
}
}
}
//通过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);
*/
}
</script>
<script src="jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() { //ready函数, 脚本加载完即执行, 也可以用$(...$("#btn").click...)();加载
$("#btn").click(function showData() { //按钮上添加onclick事件, 事件处理方法为showData()
$("#show").load("jquery.ashx"); //从jquery.ashx中获取数据元素(innerHTML的内容), 并显示在p中
});
});
</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

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

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

<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

protectedvoid Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(CalendarServices)); //AjaxPro会根据注册的类型自动生成脚本
}
Copy after login
//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
}
}
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

<%@ 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();
//由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! ");
}
});
});
});
</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

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

Ajax.Utility.RegisterTypeForAjax(typeof(SysBase_UserEdit)); //SysBase_UserEdit是页面文件名称
Copy after login
//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;
}
Copy after login
//e. Method for triggering JS by button binding

this.DDLRole.Attributes.Add("onpropertychange", "onCommandInputPropertyChange();"); //在Page_Load事件中基于Attribute为按钮绑定方法, 在aspx文件中手动添加也可以
Copy after login
//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);    
      } 
    } 
  } 
  //绑定角色名 
  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)); 
    } 
  } 
  } 
</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)

<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

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

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!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Mar 23, 2024 am 10:42 AM

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

See all articles