Home >Web Front-end >JS Tutorial >How to use ajax http request? How does ajax request the server? (Attached with example analysis)

How to use ajax http request? How does ajax request the server? (Attached with example analysis)

寻∝梦
寻∝梦Original
2018-09-10 11:21:322600browse

This article mainly talks about the basic knowledge about ajax, the history of ajax, and the basic usage of ajax. Now let us look at this article together

AJAX Basics
AJAX refers to Asynchronous JavaScript And XML (Asynchronous JavaScript And XML).
AJAX is a programming model popularized by Google in 2005.
AJAX is not a new programming language, but a new way of using existing standards.
With AJAX, you can create better, faster and more user-friendly WEB applications.
AJAX is based on JavaScript and HTTP requests (HTTP requests).
AJAX Introduction
AJAX refers to Asynchronous JavaScript And XML (Asynchronous JavaScript And XML).
Basic knowledge you should have
Before continuing, you need to have a basic understanding of the following:
* HTML / XHTML
* JavaScript
If you wish to learn these items first , please access these tutorials on our home page.
AJAX = Asynchronous JavaScript and XML (Asynchronous JavaScript and XML)
AJAX is not a new programming language, but a technology for creating better, faster and more interactive web applications.
With AJAX, your JavaScript can communicate directly with the server using JavaScript's XMLHttpRequest object. Through this
object, your JavaScript web server exchanges data. Asynchronous data transfer (HTTP requests) can be used with
AJAX between the browser and the web server without reloading the page, which allows the web page to request a small amount of information from the server, instead
not the entire page.
AJAX can make Internet applications smaller, faster, and more user-friendly.
AJAX is a browser technology that is independent of web server software.
AJAX is based on Web standards
AJAX is based on the following Web standards:
* JavaScript
* XML
* HTML
* CSS
The web standards used in AJAX are well defined , and is supported by all major browsers. AJAX applications are browser and platform independent.
AJAX IS ABOUT BETTER APPLICATIONS
Web applications have many advantages over desktop applications; they can reach a wider range of users, they are easier to install and maintain, and they are easier to develop.
However, Internet applications are not as complete and user-friendly as traditional desktop applications.
Through AJAX, Internet applications can become more complete and more friendly. (If you want to see more, go to the PHP Chinese website AJAX Development Manual column to learn)

AJAX Http request
A JAX uses Http request
in In traditional JavaScript programming, if you want to get any information from files or databases on the server, or send information to the server, you must use an HTML form to GET or POST data to the server. The user needs to click the "Submit" button to send/get the information, wait for the server's response, and then a new page will load the results.
Because the server returns a new page every time the user submits input, traditional web applications become slow and increasingly unfriendly.
By leveraging AJAX, your JavaScript communicates directly with the server through JavaScript's XMLHttpRequest object.
By using HTTP requests, a web page can make a request to the server and get a response from the server without loading the page. The user can stay on the same page and he or she will not notice that the script is requesting the page in the background or sending data to the server.
XMLHttpRequest Object
By using the XMLHttpRequest object, web developers can update pages from the server after the page has loaded!
In 2005, AJAX was promoted by Google (Google Suggest).
Google recommends using the XMLHttpRequest object to create a very dynamic web interface: when you start typing a
query into Google's search box, JavaScript sends the words to a server, which then Returns a series of search suggestions.
The XMLHttpRequest object is supported by the following browsers: Internet Explorer 5.0, Safari 1.2, Mozilla 1.0/Firefox, Opera 8, and Netscape 7.


Your first AJAX application
In order for you to understand how AJAX works, we will create a small AJAX application.

First, we need an HTML form with two text boxes: username and time. The username text box is filled in by the user, while the time text box is filled in using

AJAX.
The name of this HTML file is "testAjax.htm" (please note that this HTML form does not have a submit button!):

<html>
<body>
<form name="myForm">
用户: <input type="text" name="username" />
时间: <input type="text" name="time" />
</form>
</body>
</html>

AJAX Browser Support
AJAX - The key point of browser support for
AJAX is the XMLHttpRequest object.
Different browsers create XMLHttpRequest objects in different ways.
IE browser uses ActiveXObject, while other browsers use a JavaScript built-in object called XMLHttpRequest.
To create this object for different browsers, we need to use a "try and catch" statement. You can read more about try and catch statements in our JavaScript tutorial
.
Let's update our "testAjax.htm" file with this JavaScript that creates an XMLHttpRequest object:

<html>
<body>
<script type="text/javascript">
function ajaxFunction()
 {
        var xmlHttp;
        try{           
                    // Firefox, Opera 8.0+, Safari
                    xmlHttp=new XMLHttpRequest();
             }            
       catch (e){                 
                   // Internet Explorer                                
                   try{
                 xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                        }
                   catch (e){
                                    try{
                            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                                         }
                                   catch (e){
               return false;
                                                  }    
                                  }
                      }
}
</script>
<form name="myForm">
用户: <input type="text" name="username" />
时间: <input type="text" name="time" />
</form></body>
</html>

Example explanation:
First declare an xmlHttp variable that holds the XMLHttpRequest object.
Then use XMLHttp=new XMLHttpRequest() to create this object. This statement is for Firefox, Opera and Safari browsers.
If it fails, try xmlHttp=new ActiveXObject("Msxml2. ).
If none of these three methods work, the user is using an outdated browser and he or she will see a prompt stating that this browser does not support
AJAX.
Note: The codes for customizing the above browsers are very long and complex. However, this code will come in handy whenever you want to create an XMLHttpRequest object, so you can copy and paste this code whenever you need it. The above codes are compatible with all major browsers:
Internet Explorer, Opera, Firefox and Safari.

AJAX - XMLHttpRequest object
AJAX - More knowledge about XMLHttpRequest objectBefore sending data to the server, we need to explain the three important properties of the XMLHttpRequest object.
onreadystatechange attribute
The onreadystatechange attribute stores functions that handle server responses. The following code defines an empty function that can set the
onreadystatechange attribute at the same time:
xmlHttp.onreadystatechange=function()
{
// We need to write some code here
}
readyState attribute
readyState attribute stores the status information of the server response. Whenever readyState changes, the onreadystatechange function will be executed.
This is the possible value of the readyState attribute:
State description
0
The request is not initialized (before calling open())
1
The request has been made (before calling send()) )
2
The request has been sent (the content header can usually be obtained from the response here)
3
The request is being processed (some data is usually available in the response, but the server has not completed the response)
4
The request is complete (can access the server response and use it)

We are going to add an If statement to this onreadystatechange function to test whether our response is complete (meaning the data is available)

xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
//Get data from the server’s response
}
}
responseText attribute
The data returned by the server can be retrieved through the responseText attribute.
In our code, we will set the value of the time text box equal to responseText:
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
 {
       document.myForm.time.value=xmlHttp.responseText;
    }
}

AJAX - Request to the server
AJAX - Send a request to the serverTo send the request to the server, we need to use the open() method and send() method.
The open() method requires three parameters. The first parameter defines the method used to send the request (GET or POST). The second parameter specifies the URL of the server-side script. The third parameter specifies that the request should be processed asynchronously.
send() method sends the request to the server. If we assume that the HTML file and the ASP file are located in the same directory, then the code is like this:
xmlHttp.open("GET","time.asp",true);
xmlHttp.send(null);

Now, we must decide when to execute the AJAX function. When the user types something into the username text box, we have the function

execute "behind the scenes."

<html>
<body>
<script type="text/javascript">
function ajaxFunction()
{
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
        try
        {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e)
        {
            alert("您的浏览器不支持AJAX!");
            return false;
        }
    }
}
xmlHttp.onreadystatechange=function()
{
    if(xmlHttp.readyState==4)
    {
        document.myForm.time.value=xmlHttp.responseText;
    }
}
xmlHttp.open("GET","time.asp",true);
xmlHttp.send(null);
}
</script>
<form name="myForm">
用户: <input type="text" name="username" onkeyup="ajaxFunction();"/>
时间: <input type="text" name="time" />
</form>
</body>
</html>


AJAX - Server Side Script

Now, we are going to create a script that displays the current server time.

The responseText property stores the data returned from the server. Here we want to pass back the current time. This is the code for "time.asp":

<%response.expires=-1
response.write(time)%>

注释:Expires 属性可设置在页面缓存失效前页面被缓存的时间(分钟)。Response.Expires=-1 指示页面不会被
缓存。
运行您的 AJAX 应用程序
请在下面的文本框中键入一些文本,然后单击时间文本框:
用户 : 时间 :
时间文本框可在不加载页面的情况下从 "time.asp" 获得服务器的时间!

本篇文章到这就结束了(想看更多就到PHP中文网AJAX使用手册栏目中学习),有问题的可以在下方留言提问。

The above is the detailed content of How to use ajax http request? How does ajax request the server? (Attached with example analysis). 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