search
HomeWeb Front-endJS TutorialAjax implements asynchronous loading

Ajax implements asynchronous loading

Apr 24, 2018 pm 03:12 PM
ajaxloadaccomplish

This time I will bring you Ajax to implement asynchronous loading. What are the precautions for Ajax to implement asynchronous loading? The following is a practical case, let's take a look.

AJAX (Asynchronous JavaScript and XML, asynchronous JavaScript and XML). It's not a new

programming language, but a new way of using existing standards, the art of exchanging data with the server and updating parts of a web page without reloading the entire page.

So, let us enter the world of AJax together.

Basic Syntax

Before learning Ajax, we must clarify our needs, which is to interact with the server asynchronously and update the page without refreshing the page. information. Using Ajax is actually very simple, we just need to follow certain steps.

•Create an Ajax object (the native one needs to determine the type of the current browser)
•Set the
callback function (a function triggered after completing the interaction with the server) •Open the request, and send. (The code writing is slightly different depending on the request method)
•The client obtains feedback data and updates the page

Get the Ajax object

Different browsers Support for Ajax is inconsistent, so we have to treat it differently.

Set the callback function

The purpose of setting the callback function is to obtain the data after Ajax completes the interaction with the server information, added to the page.

Usually we specify the onreadystatechange function as our callback processing function.

Related to the interaction between Ajax and the server, there is the following status information for our reference during the coding process.

.readystate

There are several commonly used values ​​​​for the loading state:

•0: The request is not initialized
• 1: The server connection has been established
•2: The request has been received
•3: The request is being processed
•4: The request has been completed and the response is ready

.status

The status information of the loading result is:

•200: “OK”

•404: “This page was not found”

Start interaction

When talking about interaction, what comes to mind are the two parties. That is the interaction between our ajax client and server. So we need to clearly understand the location of the request data on the server

open(method,url,async)

The use of url will differ according to the method, which we must be clear about. As for the asynchronous parameter, generally speaking, false can be used for requests with a small amount of data, but it is recommended to use true for asynchronous loading to avoid excessive pressure on the server.

•GET method

This method is very simple, just specify the location of the url on the server. It is very important to understand the red part here. We must specify the URL as the location of the request on the server, usually using an absolute path.

// 对Servlet来说指定其注解上的位置即可
xmlhttp.open("GET","/Test/servlet/AjaxServlet?userinput="+str.value,true);
  xmlhttp.send();

•POST method

When using the POST method, we need an additional process. For example:

xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// 在send方法中指定要传输的参数信息即可
xmlhttp.send("fname=Bill&lname=Gates");

Client update page

For Ajax, as the name suggests. Data is transmitted in xml form. But for now, that's no longer the only form. So how do we update the obtained data to the web page? There are two ways as follows.

•If the response from the server is not XML, use the responseText attribute.
document.getElementById("myp").innerHTML=xmlhttp.responseText;

•If the response from the server is XML and needs to be parsed as an XML object, use the responseXML attribute:

xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length></x.length>";
 }
document.getElementById("myp").innerHTML=txt;

Example experience

了解了这些基础语法之后,我们就可以在实际的开发中简单的应用了。为了更好的完成此次实验,我先做了一个简单的JavaWeb,来处理我们的Ajax请求。

使用Servlet方式

AjaxServlet.java

package one;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class AjaxServlet
 */
@WebServlet("/AjaxServlet")
public class AjaxServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 /**
  * @see HttpServlet#HttpServlet()
  */
 public AjaxServlet() {
  super();
  // TODO Auto-generated constructor stub
 }
 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  *  response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  //response.getWriter().append("Served at: ").append(request.getContextPath());
  String userinput = request.getParameter("userinput");
  System.out.println("客户端连接!");
  System.out.println("请求信息为:" + userinput);
  PrintWriter out = response.getWriter();
  if(userinput.equals("") || userinput.length()the length of input string must be more than 6!");
  }else{
   response.setContentType("text/html;charset=UTF-8");
   response.setCharacterEncoding("UTF-8");
   response.setHeader("Content-Type", "text/html;charset=utf-8");
   out.println("<h3 id="Correct">Correct!</h3>");
  }
  out.close();
 }
 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  *  response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  doGet(request, response);
 }
}

 web.xml

<?xml  version="1.0" encoding="UTF-8"?>
<web-app>
 <display-name>Test</display-name>
 <welcome-file-list>
 <welcome-file>index.html</welcome-file>
 <welcome-file>index.htm</welcome-file>
 <welcome-file>index.jsp</welcome-file>
 <welcome-file>default.html</welcome-file>
 <welcome-file>default.htm</welcome-file>
 <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>
 <servlet>
 <servlet-name>AjaxServlet</servlet-name>
 <servlet-class>one.AjaxServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>AjaxServlet</servlet-name>
 <url-pattern>/servlet/AjaxServlet</url-pattern>
 </servlet-mapping>
</web-app>

ajax.html

nbsp;html>


<meta>
<title>Ajax测试</title>


<p>
 </p><h2 id="AJAX-Test">AJAX Test</h2>
 <input>
 <br>
 <span></span>
 <script>
 getResult = function(str){
  var httpxml;
  if(0 == str.value.length) {
   document.getElementById("ajax_result").innerHTML = "Nothing"; 
  } 
  if (window.XMLHttpRequest) {
   xmlhttp = new XMLHttpRequest();
  }else{
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function(){
   if(4 == xmlhttp.readyState && 200 == xmlhttp.status) {
    document.getElementById("ajax_result").innerHTML = xmlhttp.responseText;
   }
  }
  xmlhttp.open("GET","/Test/servlet/AjaxServlet?userinput="+str.value,true);
  xmlhttp.send();
  }
 </script>


实验结果
 •长度小于6时:

 •长度大于等于6:

使用JSP方式

receiveParams.jsp

 

ajax.html

nbsp;html>


<meta>
<title>Ajax测试</title>


<p>
 </p><h2 id="AJAX-Test">AJAX Test</h2>
 <input>
 <br>
 <span></span>
 <script>
 getResult = function(str){
  var httpxml;
  if(0 == str.value.length) {
   document.getElementById("ajax_result").innerHTML = "Nothing"; 
  } 
  if (window.XMLHttpRequest) {
   xmlhttp = new XMLHttpRequest();
  }else{
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function(){
   if(4 == xmlhttp.readyState && 200 == xmlhttp.status) {
    document.getElementById("ajax_result").innerHTML = xmlhttp.responseText;
   }
  }
  //xmlhttp.open("GET","/Test/servlet/AjaxServlet?userinput="+str.value,true);
  xmlhttp.open("GET","receiveParams.jsp?userinput="+str.value,true);
  xmlhttp.send();
  }
 </script>


效果一致。

JQuery 中的Ajax

前面介绍的是原生的Ajax实现方式,我们需要做的工作还是很多的,而JQuery帮助我们完成了平台无关性的工作,我们只需要专注于业务逻辑的开发即可。直接用jquery的.post或者.get或者.ajax方法,更方便更简单,js代码如下:
 •.POST方式

 $.post("./newProject",{newProjectName:project_name},
   function(data,status){
  //alert("data:" + data + "status:" + status);
  if(status == "success"){
   var nodes = data.getElementsByTagName("project");
   //alert(nodes[0].getAttribute("name"));
   for(var i = 0;i " + nodes[i].getAttribute("name") + ""); 
   }
  }
 })

 •.ajax方式

 $(function(){
  //按钮单击时执行
  $("#testAjax").click(function(){
    //Ajax调用处理
   $.ajax({
    type: "POST",
    url: "test.php",
    data: "name=garfield&age=18",
    success: function(data){
      $("#myp").html('<h2 id="data">'+data+'</h2>');
     }
   });
   });
 });

 •.get方式

 $(document).ready(function(){
 $("#bt").click(function(){
 $.get("mytest/demo/antzone.txt",function(data,status){
  alert("Data:"+data+"\nStatus:"+status);
 })
 })
})

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

jQuery+ajax功能实现

JS实现Ajax方法详解

The above is the detailed content of Ajax implements asynchronous loading. 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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software