An introduction to ajax by creating an XHR object

Time:2019-10-23

An introduction to ajax by creating an XHR object

Today, I helped my friend write a simple ajax demo and found something. I decided to write an article to record it and avoid digging holes in the future.

Create the XMLHttpRequest
usually
    function createXHR(){
        if(XMLHttpRequest){
            return new XMLHttpRequest();
        }else{
            return new ActiveXObject('Microsoft.XMLHTTP')
        }
    }

This section of js code comes from w3school and is used to create a browser-compatible XMLHttpRequest object.

Detect if the client has XMLHttpRequest, otherwise use ActiveXObject

As for the XMLHttpRequest object, IE5 is the first browser to introduce XHR object, in IE5, XHR is implemented through activeX object, so it is possible to encounter three different versions of XHR object in IE, mxsml2. XMLHTTP, mxsml2. xmlhttp.3.0 and mxsml2. xmlhttp.6.0.

The pit of IE

To pay homage to our great Internet explorer, we had to add extra code to create it
The following code applies to IE7 below:

function createXHR(){
    if(typeof argument.callee.activeXString != 'string'){
        var versions = ['MXSML2.XMLHTTP','MXSML2.XMLHttp.3.0','MXSML2.XMLHttp.6.0'];
        var i len;
        for(i = 0;len=versions.length;i<len;i++){
            try{
                new ActiveXObject(varsions[i]);
                argument.callee.activeXString = varsions[i];
            }catch{
                <! - skip -- -- >
            }
        }
    }
    return new ActiveXObject(argument.callee.activeXString);
}
Go through it all

But often I don’t think about it that much, and it’s not easy to read the function, and then let me write it, oh my god! When you and I are lazy, we can just use the first piece of code, the w3school set, and we’ll create it using native XHR objects.
Of course, we also present the complete code here.

function createXHR(){
    if(typeof XMLHttpRequest != 'undefined'){
        return new XMLHttpRequest();
    }else if(typeof argument.callee.activeXString != 'string'){
        var versions = ['MXSML2.XMLHTTP','MXSML2.XMLHttp.3.0','MXSML2.XMLHttp.6.0'];
        var i len;
        for(i = 0;len=versions.length;i<len;i++){
            try{
                new ActiveXObject(varsions[i]);
                argument.callee.activeXString = varsions[i];
            }catch{
                <! - skip -- -- >
            }
        }
        return new ActiveXObject(argument.callee.activeXString);
    }else{
        Throw new Error(" no XHR object exists ");
    }
}
usage
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>demo</title>
</head>
<body>
        <form>

        < button onclick = "returnText (); Return false"> login </button>
    </form>
    <script type="text/javascript">
        function returnText(){
            var xhr = createXHR();
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4){
                    if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
                        alert(xhr.responseText);
                    }else{
                        Alert (' get failed '+xhr.status)
                    }
                }
            }
            xhr.open('get','demo.php',true);
            xhr.send(null);

        }
        function createXHR(){
            if(typeof XMLHttpRequest != 'undefined'){
                return new XMLHttpRequest();
            }else{
                return new ActiveXObject('Microsoft.XMLHTTP')
            }
        }
    </script>
</body>
</html>

Creating the XHR object is just the first step, the beginning of our various operations.

open()

The open() function initiates a request, but it is not sent and can be viewed as preparation for doing something.
It accepts three functions:

open(get/post,url,false/true)
  1. Request types: the most common are get and post

  2. Path: the url of the file for the requested action

  3. Whether the asynchronous

We’re using get because we don’t have any data to send.
Asynchronous we selected true and accidentally found that when we used false, firefox had a warning:

Synchronous XMLHttpRequest on the main thread is no longer recommended because of its negative impact on the end-user experience.

We need to know more about it.

send()

Send () takes only one parameter, which is the data to be sent. We’re using get, no data, so null.

php

Since this article is mostly about ajax, I’ve only used the simplest echo in PHP

<?php
    Echo 'succeeded ';
 ?>

This allows you to return a string after receiving the request.

The callback function

How can we wait until the PHP file has processed the data and returned it to the client?
This is when we need to monitor the readyState property of XHR. First introduce the following readyState property:

  1. 0: initialization not completed, no call to open()

  2. 1: start the open() function, but not send

  3. 2: send, call send() function forever, has not received the response

  4. 3: start to receive and receive part of the data

  5. 4: complete, all data received.

So in the above function, we can see that we monitor the readyState property, and when it is equal to 4, that is, after receiving the data, we start to process the data.

summary

This is the easiest way to manually create an XHR object and use it. Updates will continue in the future. Describes its use in more detail.

Recommended Today

Pilot for Web

First of all, thank you @ Qibing @ zujianguo for their investment in FFW’s pre research! background Google launched the flutter for web on the latest Google I / O, aiming to further solve the problem of one-time code and multi-terminal operation. Flutter for web is still in the early pilot version and is not […]