Ajax (Asynchronous JavaScript + XML) Technology Learning

Source: Internet
Author: User
Tags object model response code tld

Reference Document: Https://developer.mozilla.org/en-US/docs/AJAX This article has been roughly translated. Ajax itself is not a technology, but in 2005 by Jesse James Garrett pioneered the description of a "new" approach to apply many existing technologies, including: HTML or XHTML, cascading Style Sheets, JavaScript, the Document object Model, XML, XSLT, and the most important XMLHttpRequest object. When these technologies are incorporated into the AJAX model, the Web app can quickly and incrementally update the user interface to replace the previous refresh of the entire browsing interface, which makes the application faster and the user experience better. Although X in Ajax represents Xml,json, it is more used because of its lightness and the advantages of being part of JavaScript. The JSON and XML inside the AJAX model are used to wrap the data information. What is Ajax? AJAX represents asynchronous JavaScript and XML. In short, he is using xmlhttprequestobject to communicate with the server in a way. It can send and receive information in different ways, including JSON, XML, HTML, and text files. The most attractive feature of Ajax is "async", which means it can communicate with the server and Exchange data Update pages without refreshing the page. The main two main features of Ajax:
    • Do not refresh page request data
    • Getting data from the server
Step: How to request a server in order to use JavaScript, we instantiate an object that has the necessary functionality. This is the source of XMLHttpRequest. At first, Internet Explorer implemented an ActiveX object called XMLHTTP. Later, Mozilla, Safari, and other browser vendors implemented the XMLHttpRequest object to support this approach and the Microsof-like ActiveX object functionality.  At the same time, Microsoft has 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 only explains it, but it only creates instances of XMLHTTP 。 You can skip to step 3 to see more practical examples. After the request, we need to receive the request result. At this stage, we need to tell the XMLHTTP request object to handle the response of the JavaScript method by configuring his Onreadystatechangeproperty method, as follows:
httpRequest.onreadystatechange = nameOfTheFunction;
Or
httpRequest.onreadystatechange = function(){
// Process the server response here.
};
After declaring how to accept the response, we need to initiate the request by invoking the open () and send () methods of the HTTP request object as follows:
httpRequest.open(‘GET‘, ‘http://www.example.org/some.file‘, true);
httpRequest.send();
    • The first parameter of open () is the method that the HTTP request –get, POST, HEAD, or other server supports. Method names all caps are HTTP standards, or some browsers (for example, Firefox) may not request a sender. Click on the specs for more information on the HTTP request method.
    • The second parameter is the URL to be requested. From a security perspective, it is not possible to request URLs across domains by default. Make sure all pages are under the same domain name, or call the open () method, you will get "Permission denied" error. A common cross-domain is that your site's domain name is domain.tld, but try to access the page with Www.domain.tld. If you really want to cross-domain requests, view HTTP access control.
    • The optional third parameter sets whether the request is synchronous or asynchronous. If True (the default), JavaScript continues to execute, and the server returns data while the user is manipulating the page. This is Ajax's a.
The parameters of the Send () method can be any data (POST) that you want to send to the server. The form data must be a form that the server can parse, such as a query string:
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
or other forms, such as Multipart/form-data,json, XML, and so on. Note If you want to post data, you may want to set the requested MIME type. For example, we put the following code before calling send () to send the form data when the query data is sent:
httpRequest.setRequestHeader(‘Content-Type‘, ‘application/x-www-form-urlencoded‘);
We have provided the JavaScript method for handling the response when the Step is processing the server response request:
httpRequest.onreadystatechange = nameOfTheFunction;
What does this method do? First, we need to check the request status. If the table value is Xmlhttprequest.done (4), it means that all servers have been accepted for the sound.
if (httpRequest.readyState === XMLHttpRequest.DONE) {
// Everything is good, the response was received.
} else {
// Not ready yet.
}
ReadyState all possible values, which can be viewed in Xmlhttprequest.readystate, as follows:
    • 0 (uninitialized) or (Request uninitialized)
    • 1 (loading) or (server established connection)
    • 2 (loaded) or (request received)
    • 3 (in teractive) or (execution request)
    • 4 (complete) or (request finished and response are ready request completion response in place)
    • Td>unsent
      Value State Description
      0 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 is available.
      3 LOADING downloading; responsetext holds Partial data
      4 done the operation are complete.
Next, check the HTTP response's response code. See the possible values for the view. In the following example we use response code is not equal to 200来 to determine whether the AJAX request is successful.
if (httpRequest.status === 200) {
// Perfect!
} else {
// There was a problem with the request.
// For example, the response may have a 404 (Not Found)
// or 500 (Internal Server Error) response code.
}
After the response value has been checked. We are free to handle the data returned by the server, with two choices to obtain this data:
    • httprequest.responsetext– Return Server response string
    • httprequest.responsexml– return Server Response XmlDocument object can be passed to JavaScript DOM method
The above code is valid only in the case of async (the third parameter of open () is set to true). If you use synchronous requests, there is no need to specify a method. However, we do not encourage the use of synchronization requests because synchronization can lead to a very poor user experience. Step 3– A simple example where we put the above together to synthesize a simple HTTP request. Our JavaScript will request an HTML document, Test.html, containing a string "I ' m a test." Then we respond to the content with alert (). This example uses normal javascript-without introducing jquery, HTML, XML and PHP files should be placed in the same level directory.
<button id="ajaxButton" type="button">Make a request</button>

<script>
(function() {
var httpRequest;
document.getElementById("ajaxButton").addEventListener(‘click‘, makeRequest);

function makeRequest() {
httpRequest = new XMLHttpRequest();

if (!httpRequest) {
alert(‘Giving up :( Cannot create an XMLHTTP instance‘);
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open(‘GET‘, ‘test.html‘);
httpRequest.send();
}

function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert(‘There was a problem with the request.‘);
}
}
}
})();
</script>
In this example:
    • The user clicks on the "Make a Request" button;
    • Event Call MakeRequest () method;
    • The request is issued, and then (onreadystatechange) execution is passed to alertcontents ();
    • Alertcontents () checks if the response is OK, and then alert () test.html the file contents.
Note 1: If the server returns XML instead of a static XML file, you must set response headers to be compatible with i.e.  If you do not set Headercontent-type:application/xml, IE will throw a JavaScript "Object expected" error after you try to get the XML element. NOTE 2: If you do not set the header cache-control:no-cache the browser will cache the response without submitting the request again, which is difficult to debug. You can add always different get parameters, such as timestamp or random numbers (see bypassing the cache) Note 3: If the HttpRequest variable is global, the promiscuous call MakeRequest () overwrites the respective request, resulting in a The state of competition. Declare HttpRequest local variables in a closure to avoid this problem. In the event of a communication error (such as a server crash), the onReadyStateChange method throws an exception when the response state is accessed. To alleviate this problem, you can use Ry...catch to wrap your if...then statement:
function alertContents() {
try {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert(‘There was a problem with the request.‘);
}
}
}
catch( e ) {
alert(‘Caught Exception: ‘ + e.description);
}
}
Step 4– using XML response in the previous example, after getting the response, we used the Request object ResponseText property to get the test.html file content. Now let's try to get the Responsexml property. First, let's create a valid XML document and leave it to our request later. (Test.xml) is as follows:
<?xml version="1.0" ?>
<root>
I‘m a test.
</root>
In this script, we just need to modify the request behavior:
...
onclick="makeRequest(‘test.xml‘)">
...
Then in Alertcontents (), we need to put alert (httprequest.responsetext); Change to:
var xmldoc = httpRequest.responseXML;
var root_node = xmldoc.getElementsByTagName(‘root‘).item(0);
alert(root_node.firstChild.data);
This gets the Responsexml XmlDocument, and then uses the DOM method to get the content contained in the XML document. You can view the Test.xml in here and view the modified script here. Step 5– using data to return Finally, let's send some data to the server and then get a response. Our JavaScript will request a dynamic page this time, test.php will fetch the data we send and return a computed string-"Hello, [user data]!", then we alert (). First we add a text box to the HTML, the user can enter their name:

<input type="text" id="ajaxTextbox" />
</label>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>
We also add a line to the event handling method to get the text box content and pass it along with the URL of the server-side script to the MakeRequest () method:
  
var userName = document.getElementById("ajaxTextbox").value;

};
We need to modify the MakeRequest () method to accept user data and pass it to the server. We will change the method from get to POST, and wrap our data into Parameters Httprequest.send ():
function makeRequest(url, userName) {

...

httpRequest.onreadystatechange = alertContents;
httpRequest.open(‘POST‘, url);
httpRequest.setRequestHeader(‘Content-Type‘, ‘application/x-www-form-urlencoded‘);
httpRequest.send(‘userName=‘ + encodeURIComponent(userName));
}
If the server returns only one string, the Alertcontents () method can be the same as step 3. However, the server not only returns the computed string, but also returns the original user name. So if we enter "Jane" in the input box, the return of the server will look like this: {"UserData": "Jane", "computedstring": "Hi, jane!"} To use data in alertcontents (), we cannot directly alert ResponseText, we must convert the data and then alert Computedstring property:
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
alert(response.computedString);
} else {
alert(‘There was a problem with the request.‘);
}
}
}
The test.php file is as follows:
$name = (isset($_POST[‘userName‘])) ? $_POST[‘userName‘] : ‘no name‘;
$computedString = "Hi, " . $name;
$array = [‘userName‘ => $name, ‘computedString‘ => $computedString];
echo json_encode($array);
To see more DOM methods, see the Mozilla's DOM implementation documentation.

Ajax (Asynchronous JavaScript + XML) Technology Learning

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.