search
HomeWeb Front-endJS TutorialWhat is ajax? A detailed introduction to ajax

What is ajax? A detailed introduction to ajax

Jun 26, 2017 am 10:29 AM
ajaxjavascriptjsstudytechnology

Ajax itself is not a technology, but was pioneered by Jesse James Garrett in 2005 and described as a "new" way to apply many existing technologies, including: HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, and most importantly the XMLHttpRequest object.

When these technologies are combined into the Ajax model, the web app can quickly and gradually update the user interface instead of refreshing the entire browsing interface, which makes the application faster and user experience better. better.
Although x represents xml in ajax, json is used more because of its advantages of being lighter and being part of javascript. Both json and xml in the ajax model are used to package data information.

What is AJAX?

AJAX stands for Asynchronous JavaScript And XML. In short, it uses XMLHttpRequestobject to communicate with the server. It can be used in different ways Methods to send and receive information, including JSON, XML, HTML, and text files. The most attractive feature of AJAX is "asynchronous", which means that it can communicate with the server and exchange data to update the page without refreshing the page.
The main two main features of ajax:
  • Do not refresh the page to request data

  • From The server gets data

Step 1 – How to request

In order to request the server using javascript, we need to instantiate an object with the necessary functions. This is where XMLHttpRequest comes from. Originally Internet Explorer implemented an ActiveX object called XMLHTTP. Since then, Mozilla, Safari, and other browser manufacturers have successively implemented the XMLHttpRequest object to support this method and ActiveX object functions similar to Microsoft's. At the same time, Microsoft also implemented XMLHttpRequest.
// Old compatibility code, no longer needed.
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ .. .
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP ");
}
Note: The above code is for explanation only and only creates an instance of XMLHttp. You can skip to step 3 to see more practical examples.
After requesting, we need to receive the request result. At this stage, we need to tell the XMLHttp request object to handle the response JavaScript method, by configuring its onreadystatechangeproperty method, as follows:
httpRequest.onreadystatechange = nameOfTheFunction;
or
<code>httpRequest.onreadystatechange = function(){<br>    // Process the server response here.<br>};</code>
After declaring how to accept the response, we need Initiate a request by calling the open() and send() methods of the HTTP request object, as follows:
<code>httpRequest.open('GET', 'http://www.example.org/some.file', true);<br>httpRequest.send();</code>
  • The first parameter of open() is the HTTP request method – GET, POST , HEAD, or other methods supported by the server. Method names in all capital letters are HTTP standards, otherwise some browsers (for example: Firefox) may not issue the request. Click W3C specs for more information about http request methods.

  • The second parameter is the url to be requested. For security reasons, cross-domain URL requests cannot be made by default. Make sure all pages are under the same domain name, otherwise you will get a "permission denied" error when calling the open() method. A common cross-domain problem is that your website's domain name is domain.tld, but you try to access the page using www.domain.tld. If you really want to make cross-origin requests, check out HTTP access control.

  • The optional third parameter sets whether the request is synchronous or asynchronous. If it is true (default value), JavaScript will continue to execute, and the server will return data while the user operates the page. This is the AJAX.

The parameters of the send() method can be any data (POST) you want to send to the server. The form data must be in a form that the server can parse, such as query string:
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
or other forms, such as multipart/form-data, JSON, XML, etc.
Note that if you want to POST data, you may have to set the requested MIME type. For example, we put the following code before calling send() to send the form data as query data:
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

Step 2 - When processing the server response to the

request, we have provided processing Response JavaScript method:
httpRequest.onreadystatechange = nameOfTheFunction;
What does this method do? First, we need to check the request status. If the value is XMLHttpRequest.DONE (4), it means that all server responses have been accepted.
<code>if (httpRequest.readyState === XMLHttpRequest.DONE) {<br>    // Everything is good, the response was received.<br>} else {<br>    // Not ready yet.<br>}</code>
All possible values ​​of readyState can be viewed in XMLHTTPRequest.readyState, as follows:
  • 0 (uninitialized) or (the request is not initialized)

  • 1 (loading) or (the server establishes a connection)

  • 2 (loaded) or (request received)

  • 3 (interactive) or (execution request)

  • 4 (complete) or (request finished and response is readyrequest completed response in place)

  • ##3LOADINGDownloading; responseText holds partial data.4DONEThe operation is complete.
    (Source)
    接下来,检查HTTP响应的 response code 。查看 W3C看到可能的值。下面例子我们用response code是不是等于200来判断ajax请求是否成功。
    <code>if (httpRequest.status === 200) {<br>    // Perfect!<br>} else {<br>    // There was a problem with the request.<br>    // For example, the response may have a 404 (Not Found)<br>    // or 500 (Internal Server Error) response code.<br>}</code>
    检查完响应值后。我们可以随意处理服务器返回的数据,有两个选择获得这些数据:
    • httpRequest.responseText – 返回服务器响应字符串

    • httpRequest.responseXML – 返回服务器响应XMLDocument 对象 可以传递给JavaScript DOM 方法

    上面的代码只有在异步的情况下有效(open() 的第三个参数设置为true)。如果你用同步请求,就没必要指定一个方法。但是我们不鼓励使用同步请求,因为同步会导致极差的用户体验。

    Step 3 – 一个简单的例子

    我们把上面的放在一起合成一个简单的HTTP请求。我们的JavaScript 将请求一个HTML 文档, test.html, 包含一个字符串 "I'm a test."然后我们alert()响应内容。这个例子使用普通的JavaScript — 没有引入jQuery, HTML, XML 和 PHP 文件应该放在同一级目录下。
    <code><button id="ajaxButton" type="button">Make a request</button><br><br><script><br/>(function() {<br/>  var httpRequest;<br/>  document.getElementById("ajaxButton").addEventListener(&#39;click&#39;, makeRequest);<br/><br/>  function makeRequest() {<br/>    httpRequest = new XMLHttpRequest();<br/><br/>    if (!httpRequest) {<br/>      alert(&#39;Giving up :( Cannot create an XMLHTTP instance&#39;);<br/>      return false;<br/>    }<br/>    httpRequest.onreadystatechange = alertContents;<br/>    httpRequest.open(&#39;GET&#39;, &#39;test.html&#39;);<br/>    httpRequest.send();<br/>  }<br/><br/>  function alertContents() {<br/>    if (httpRequest.readyState === XMLHttpRequest.DONE) {<br/>      if (httpRequest.status === 200) {<br/>        alert(httpRequest.responseText);<br/>      } else {<br/>        alert(&#39;There was a problem with the request.&#39;);<br/>      }<br/>    }<br/>  }<br/>})();<br/></script></code>
    在这个例子里:
    • 用户点击"Make a request” 按钮;

    • 事件调用 makeRequest() 方法;

    • 请求发出,然后 (onreadystatechange)执行传递给 alertContents();

    • alertContents() 检查响应是否 OK, 然后 alert() test.html 文件内容。

     
     
    注意 1: 如果服务器返回XML,而不是静态XML文件,你必须设置response headers 来兼容i.e.。如果你不设置headerContent-Type: application/xml, IE 将会在你尝试获取 XML 元素之后抛出一个JavaScript "Object Expected" 错误 。
     
     
    注意 2: 如果你不设置header Cache-Control: no-cache 浏览器将会缓存响应不再次提交请求,很难debug。你可以添加永远不一样的GET 参数,例如 timestamp 或者 随机数 (查看 bypassing the cache)
     
    注意 3: 如果 httpRequest 变量是全局的,混杂调用 makeRequest()会覆盖各自的请求,导致一个竞争的状态。在一个closure 里声明 httpRequest 本地变量 来避免这个问题。
    在发生通信错误(如服务器崩溃)、onreadystatechange方法会抛出一个异常,当访问响应状态。为了缓解这个问题,你可以用ry…catch包装你的if...then 语句:
    <code>function alertContents() {<br>  try {<br>    if (httpRequest.readyState === XMLHttpRequest.DONE) {<br>      if (httpRequest.status === 200) {<br>        alert(httpRequest.responseText);<br>      } else {<br>        alert('There was a problem with the request.');<br>      }<br>    }<br>  }<br>  catch( e ) {<br>    alert('Caught Exception: ' + e.description);<br>  }<br>}</code>

    Step 4 – 使用 XML 响应

    在前面的例子里,在获取到响应之后,我们用request 对象responseText 属性获得 test.html 文件内容。现在让我们尝试获取responseXML 属性。
    首先,让我们创建一个有效的XML文档,留着待会我们请求。(test.xml)如下:
    <code><?xml version="1.0" ?><br><root><br>    I'm a test.<br></root></code>
    在这个脚本里,我们只要修改请求行为:
    <code>...<br>onclick="makeRequest('test.xml')"><br>...</code>
    然后在alertContents()里,我们需要把 alert(httpRequest.responseText); 换为:
    <code>var xmldoc = httpRequest.responseXML;<br>var root_node = xmldoc.getElementsByTagName('root').item(0);<br>alert(root_node.firstChild.data);</code>
    这里获得了responseXML的XMLDocument,然后用 DOM 方法来获得包含在XML文档里面的内容。你可以在here查看test.xml,在here查看修改后的脚本。

    Step 5 – 使用数据返回

    最后,让我们来发送一些数据到服务器,然后获得响应。我们的JavaScript这次将会请求一个动态页面,test.php将会获取我们发送的数据然后返回一个计算后的字符串 - "Hello, [user data]!",然后我们alert()出来。
    首先我们加一个文本框到HTML,用户可以输入他们的姓名:
    <code><label>Your name: <br>  <input type="text" id="ajaxTextbox"><br></label><br><span id="ajaxButton" style="cursor: pointer; text-decoration: underline"><br>  Make a request<br></span></code>
    我们也给事件处理方法里面加一行获取文本框内容,并把它和服务器端脚本的url一起传递给 makeRequest() 方法:
    <code>  document.getElementById("ajaxButton").onclick = function() { <br>      var userName = document.getElementById("ajaxTextbox").value;<br>      makeRequest('test.php',userName); <br>  };</code>
    我们需要修改makeRequest()方法来接受用户数据并且传递到服务端。我们将把方法从 GET 改为 POST,把我们的数据包装成参数放到httpRequest.send():
    <code>function makeRequest(url, userName) {<br><br>    ...<br><br>    httpRequest.onreadystatechange = alertContents;<br>    httpRequest.open('POST', url);<br>    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');<br>    httpRequest.send('userName=' + encodeURIComponent(userName));<br>  }</code>
    如果服务端只返回一个字符串, alertContents() 方法可以和Step 3 一样。然而,服务端不仅返回计算后的字符串,还返回了原来的用户名。所以如果我们在输入框里面输入 “Jane”,服务端的返回将会像这样:
    {"userData":"Jane","computedString":"Hi, Jane!"}
    要在alertContents()使用数据,我们不能直接alert responseText, 我们必须转换数据然后 alert computedString属性:
    <code>function alertContents() {<br>  if (httpRequest.readyState === XMLHttpRequest.DONE) {<br>    if (httpRequest.status === 200) {<br>      var response = JSON.parse(httpRequest.responseText);<br>      alert(response.computedString);<br>    } else {<br>      alert('There was a problem with the request.');<br>    }<br>  }<br>}</code>
    test.php 文件如下:
    <code>$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';<br>$computedString = "Hi, " . $name;<br>$array = ['userName' => $name, 'computedString' => $computedString];<br>echo json_encode($array);</code>
    查看更多DOM方法, 请查看 Mozilla's DOM implementation 文档。
    Value State Description
    0 UNSENT Client has been created. open() not called yet.
    1 OPENED open() has been called.
    2 HEADERS_RECEIVED send() has been called, and headers and status are available.

The above is the detailed content of What is ajax? A detailed introduction to 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
Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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.

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft