Home > Web Front-end > JS Tutorial > body text

What is ajax? A detailed introduction to ajax

零下一度
Release: 2017-06-26 10:29:37
Original
988 people have browsed it

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;
Copy after login
Copy after login
or
<code>httpRequest.onreadystatechange = function(){<br>    // Process the server response here.<br>};</code>
Copy after login
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>
Copy after login
  • 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"
Copy after login
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');
Copy after login

Step 2 - When processing the server response to the

request, we have provided processing Response JavaScript method:
httpRequest.onreadystatechange = nameOfTheFunction;
Copy after login
Copy after login
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>
Copy after login
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>
    Copy after login
    检查完响应值后。我们可以随意处理服务器返回的数据,有两个选择获得这些数据:
    • 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('click', makeRequest);<br><br>  function makeRequest() {<br>    httpRequest = new XMLHttpRequest();<br><br>    if (!httpRequest) {<br>      alert('Giving up :( Cannot create an XMLHTTP instance');<br>      return false;<br>    }<br>    httpRequest.onreadystatechange = alertContents;<br>    httpRequest.open('GET', 'test.html');<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('There was a problem with the request.');<br>      }<br>    }<br>  }<br>})();<br></script></code>
    Copy after login
    在这个例子里:
    • 用户点击"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>
    Copy after login

    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>
    Copy after login
    在这个脚本里,我们只要修改请求行为:
    <code>...<br>onclick="makeRequest('test.xml')"><br>...</code>
    Copy after login
    然后在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>
    Copy after login
    这里获得了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>
    Copy after login
    我们也给事件处理方法里面加一行获取文本框内容,并把它和服务器端脚本的url一起传递给 makeRequest() 方法:
    <code>  document.getElementById("ajaxButton").onclick = function() { <br>      var userName = document.getElementById("ajaxTextbox").value;<br>      makeRequest('test.php',userName); <br>  };</code>
    Copy after login
    我们需要修改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>
    Copy after login
    如果服务端只返回一个字符串, 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>
    Copy after login
    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>
    Copy after login
    查看更多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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template