What is ajax? A detailed introduction to ajax
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.
What is AJAX?
Do not refresh the page to request data
From The server gets data
Step 1 – How to request
httpRequest.onreadystatechange = nameOfTheFunction;
<code>httpRequest.onreadystatechange = function(){<br> // Process the server response here.<br>};</code>
<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.
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Step 2 - When processing the server response to the
httpRequest.onreadystatechange = nameOfTheFunction;
<code>if (httpRequest.readyState === XMLHttpRequest.DONE) {<br> // Everything is good, the response was received.<br>} else {<br> // Not ready yet.<br>}</code>
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)
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. ##3 LOADING Downloading; responseText holds partial data. 4 DONE The 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 loginStep 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 logintest.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 文档。
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

This paper explores the problem of accurately detecting objects from different viewing angles (such as perspective and bird's-eye view) in autonomous driving, especially how to effectively transform features from perspective (PV) to bird's-eye view (BEV) space. Transformation is implemented via the Visual Transformation (VT) module. Existing methods are broadly divided into two strategies: 2D to 3D and 3D to 2D conversion. 2D-to-3D methods improve dense 2D features by predicting depth probabilities, but the inherent uncertainty of depth predictions, especially in distant regions, may introduce inaccuracies. While 3D to 2D methods usually use 3D queries to sample 2D features and learn the attention weights of the correspondence between 3D and 2D features through a Transformer, which increases the computational and deployment time.

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

When editing text content in Word, you sometimes need to enter formula symbols. Some guys don’t know how to input the root number in Word, so Xiaomian asked me to share with my friends a tutorial on how to input the root number in Word. Hope it helps my friends. First, open the Word software on your computer, then open the file you want to edit, and move the cursor to the location where you need to insert the root sign, refer to the picture example below. 2. Select [Insert], and then select [Formula] in the symbol. As shown in the red circle in the picture below: 3. Then select [Insert New Formula] below. As shown in the red circle in the picture below: 4. Select [Radical Formula], and then select the appropriate root sign. As shown in the red circle in the picture below:

In September 23, the paper "DeepModelFusion:ASurvey" was published by the National University of Defense Technology, JD.com and Beijing Institute of Technology. Deep model fusion/merging is an emerging technology that combines the parameters or predictions of multiple deep learning models into a single model. It combines the capabilities of different models to compensate for the biases and errors of individual models for better performance. Deep model fusion on large-scale deep learning models (such as LLM and basic models) faces some challenges, including high computational cost, high-dimensional parameter space, interference between different heterogeneous models, etc. This article divides existing deep model fusion methods into four categories: (1) "Pattern connection", which connects solutions in the weight space through a loss-reducing path to obtain a better initial model fusion

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Written above & The author’s personal understanding is that image-based 3D reconstruction is a challenging task that involves inferring the 3D shape of an object or scene from a set of input images. Learning-based methods have attracted attention for their ability to directly estimate 3D shapes. This review paper focuses on state-of-the-art 3D reconstruction techniques, including generating novel, unseen views. An overview of recent developments in Gaussian splash methods is provided, including input types, model structures, output representations, and training strategies. Unresolved challenges and future directions are also discussed. Given the rapid progress in this field and the numerous opportunities to enhance 3D reconstruction methods, a thorough examination of the algorithm seems crucial. Therefore, this study provides a comprehensive overview of recent advances in Gaussian scattering. (Swipe your thumb up
