This is the sixth day of my participation in Gwen Challenge

This article will help you get to the bottom of where Ajax comes from, but it won’t help you break down its encapsulation.

Implement an AJAX asynchronous call and local refresh

  1. Create an XMLHttpRequest object, that is, create an asynchronous call object
  2. Create a new HTTP request and specify the HTTP request method and URL
  3. Sets the function that responds to changes in the status of HTTP requests

As a front-end developer, you must first understand XMLHttpRequest

XMLHttpRequest

XMLHttpRequest A technique that supports asynchronous requests and is at the heart of Ajax

Requests can be made to the server and responses processed without blocking the user

You can update parts of a page after it has loaded

Create an XMLHttpRequest object

var xmlHttp;
if(window.XMLHttpRequest){
    xmlHttp = new XMLHttpRequest();
}else{
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")}console.log(xmlHttp)
Copy the code

Of course, you can write a more detailed judgment, for example

function createXHR() {
    if (typeofXMLHttpRequest ! ="undefined") {
        return new XMLHttpRequest();
    } else if (typeofActiveXObject ! = ="undefined") {
        var xhrArr = ['Microsoft.XMLHTTP'.'MSXML2. XMLHTTP. 6.0'.'MSXML2. XMLHTTP. 5.0'.'MSXML2. XMLHTTP. 4.0'.'MSXML2. XMLHTTP. 3.0'.'MSXML2. XMLHTTP. 2.0']
        var len = xhrArr.length;
        var xhr;
        for (var i = 0; i < len; i++) {
            try {
                xhr = new ActiveXObject(xhrArr[i]);
                break;
            } catch (ex) {

            }
        }
        return xhr;
    }else {
        throw new Error('No XHR object availabel.')}}var xhr = createXHR();
console.log(xhr);
Copy the code

How do I create an HTTP request

  • Grammar: open (method, url, async)
  • Function: Creates an HTTP request, specifying the type of request, URL, and whether to process the request asynchronously
  • Parameters:
    • Method: Request type, GET or POST
    • Address of the url:
    • Async: true or false

The open method does not send an actual request to the server, it is equivalent to initializing the request and preparing to send it only to urls that use the same protocol and port in the same domain, otherwise an error will be reported for security reasons.

xmlHttp.open("get"."./server/slider.json".true)
xmlHttp.open("post"."./server/slider.json".true)
Copy the code

GET vs. POST

GET is simpler and faster than POST, and works in most cases. However, POST requests must be used in the following cases:

  • Unable to use cached files (updating files or databases on the server)
  • Sending large amounts of data to the server (POST has no data limit)
  • POST is more stable and reliable than GET when sending user input that contains unknown characters

The difference between synchronous and asynchronous

Sync: Submit the request -> wait for the server to process it -> return the client browser cannot do anything during this time

Asynchronous: The request is triggered by an event -> server processing (this is where the browser can still do other things)-> processed

How to send a request

  • Grammar: send (string)
  • Function: Sends a request to the server
  • Parameter: String is only used for POST requests. Parameters can only be passed in post requests. Null is sent if they are not needed.

Sample code is written below.

How do I add HTTP headers

  • If you want to POST data like an HTML form, use setRequestHeader() to add the HTTP header, and then specify what data you want to send in the send() method
  • Grammar: xmlHttp. SetRequestHeader (header, value)
  • Use: xmlHttp. SetRequestHeader (” the content-type “, “application/x – WWW – form – urlencoded”);
xmlHttp.open("get"."./server/slider.json? username=zhangsan&id=666".true)
xmlHttp.send(null)

xmlHttp.open("post"."./server/slider.json".true)
// Post request parameters
xmlHttp.send({username:"zhangsan".id:"666"})
/ / request header
xmlHttp.setRequestHeader("Content-type"."application/x-www-form-urlencoded");
Copy the code

Sets the function that responds to changes in the status of HTTP requests

After receiving the response, the corresponding data is populated with the attributes of the XHR object. Four related attributes are populated:

  • ResponseText — a string of data returned from the server process
  • ResponseXML — DOM compliant document data object returned from the server process
  • Status – Numeric codes returned from the server, such as 404(not found), 200(ready)
  • Status Text – String information that accompanies the status code
// A function that responds to a statechange in the XMLHttpRequest object. Onreadystatechange is triggered when the readyStatechange property sends a change
xmlHttp.onreadystatechange = function () {
    // The asynchronous call succeeds, and the response content is parsed successfully
    if (xmlHttp.readyState === 4) {
        if ((xmlHttp.status >= 200 && xmlHttp.status < 300) || xmlHttp.status === 304) {
            // Get the data returned by the server
            console.log(xmlHttp.responseText); }}}Copy the code

JSON data text

JSON(javascript Object notation) is a text format for data exchange, rather than a programming language for reading structured data. It was developed by Douglas Crockford in 2001. The goal is to replace cumbersome XML formats.

JSON syntax can represent three types of values:

Simple values

Simple values use the same syntax as JavaScript and can represent strings, values, booleans, and NULL in JSON

Strings must be expressed in double quotes, not single quotes, values must be expressed in decimal, and NaN and Infinity cannot be used

JSON does not support the special value of undefined in JavaScript

object

Object, as a complex data type, represents an ordered set of key-value pairs, and the values in each key-value pair can be simple values or values of complex data types

The key names of objects in JSON must be enclosed in double quotes, because JSON is not a javascript statement, so there is no trailing semicolon

Note: Two attributes with the same name should not appear in the same object

An array of

An array is also a complex data type that represents an ordered list of values that can be accessed by a numeric index

Note: The last member of an array or object cannot be followed by a comma

{
    "name": "BeJson"."url": "http://www.bejson.com"."page": 88."isNonProfit": true."address": {
        "street": "Science Park Road."."city": "Suzhou, Jiangsu"."country": "China"
    },
    "links": [{"name": "Google"."url": "http://www.google.com"
        },
        {
            "name": "Baidu"."url": "http://www.baidu.com"
        },
        {
            "name": "SoSo"."url": "http://www.SoSo.com"}}]Copy the code

As we mentioned earlier, responseText returns a string, which is not usable by our JAVASCRIPT code, so we need to convert it to a data type that we can manipulate. There are two methods in the JSON object that allow us to do this quickly.

Two methods

parse()

  • Grammar: JSON. The parse ()

  • Function: Convert A JSON string to an object

stringify()

  • Grammar: JSON. Stringify ()
  • Function: Convert a value to a string that conforms to JSON format and can be restored by the json.parse () method

JSON is popular because you can parse JSON data structures into useful javascript objects

The stringify() and parse() methods for JSON objects can be used to serialize JavaScript objects into JSON strings and parse JSON strings into native JavaScript values, respectively

JavaScript eval() is similar to the json.parse () method, which converts A JSON string into a JSON object. However, eval() can execute code that does not conform to the JSON format and may contain malicious code

Rendering data, there are many ways to render, the more concise is generally the use of string loops for stitching after passing HTML, sample code

 <div class="banner" id="banner"></div>

// Render data
function renderDataToDom() {
    var img = data.slider,
        i, len = img.length,
        str = "",
        banner = document.getElementById("banner")
    for (i = 0; i < len; i++) {
        str += '<a href="' + img[i].linkUrl + '"><img src="./' + img[i].picUrl + '"></a>'
    }
    console.log(str)
    banner.innerHTML = str
}
Copy the code

JQuery ajax method

<div class="banner" id="banner"></div>
<script src=". / js/jquery - 1.7.1. Js. ""></script>
<script>
    .ajax({
        url: "./server/slider.json".// Request an address
        type: "get".// Request type
        async: true.// Synchronize asynchronously
        dataType: "json".// Return the data type
        success: function (data) {   // Callback after successful request
            // Data rendering
            renderDataToDom(data.slider)
        },
        error: function (error) {
            console.log(error)
        }
    })
    // Data rendering
    function renderDataToDom(data) {
        var str = ""
        $.each(data, function (index, item) {
            str += `<a href="${item.linkUrl}"><img src="./${item.picUrl}"></a>`$(})"#banner").html(str)
    }
</script>
Copy the code

To solve the cross domain

The cross-domain problem is a classic one, but if you haven’t seen it before, you can see it here

As we all know: Ajax direct requests to common files have no permission to access the problem, regardless of whether you are static pages, dynamic pages, Web services, WCF, as long as it is a cross-domain request, will not pass.

How can you use JSONP to solve cross-domain problems

JSONP, short for JSONwith Padding, is a new way to apply JSON and a cross-domain solution.

It is not possible to request data on different domains directly with XMLHttpRequest. However, it is possible to introduce JS script files from different domains on the page, and jSONP takes advantage of this feature.

The principle of the json

Import the JS file via the script tag -> After the js file has been successfully loaded -> execute the function we specified in the URL argument

The composition of the json

JSONP consists of two parts: callback functions and data. The callback function is the function that should be called in the page when the response arrives, and the data is the JSON data passed in to the callback function.

/ / encapsulates the json
function getJSONP(url, callback) {
    if(! url) {return;
    }
    var r = ['a'.'b'.'c'.'d'.'e'.'f'.'g'.'h'.'i'.'j'.'k'],
        r1 = Math.floor(Math.random() * 10),
        r2 = Math.floor(Math.random() * 10),
        r3 = Math.floor(Math.random() * 10),
        name = 'getJSONP' + r[r1] + r[r2] + r[r3],
        // Use getJSONP. This should be the same as the function name
        cbName = 'getJSONP.' + name;
    if (url.indexOf('? ') = = = -1) {
        url += '? jsonp=' + cbName;
    } else {
        url += '&jsonp=' + cbName;
    }
    // Dynamically create script tags
    var script = document.createElement('script');
    // Define the callback function executed by the script
    // https://www.xn2001.com/?jsonp=getJSONP.getJSONPejg
    getJSONP[name] = function (data) {
        try {
            callback && callback(data);
        } catch (error) {
            console.log(error);
        } finally {
            // Finally delete the function and the script tag
            delete getJSONP[name];
            script.parentNode.removeChild(script)
        }
    }

    // Define script SRC
    script.src = url;
    document.getElementsByTagName("head") [0].appendChild(script);

}
getJSONP("https://class.imooc.com/api/jsonp".function (data) {
    console.log(data);
})
Copy the code

How to understand the working principle from js perspective?

After stitching, the requested address is: https://class.imooc.com/api/jsonp?jsonp=getJSONP.getJSONPejg – > the data returned to getJSONP getJSONPcjf + (json data) – > Find the getJSONPcjf function under getJSONP to carry the data -> pass the data to the callback function for us to use -> remove the tainted SRC and function etc

So JSONP is not really Ajax, taking advantage of the fact that js files are called with no cross-domain influence.

How to use JSONP in JQuery, add a parameter and change the data return type -> JSONP, dataType

$.ajax({
    url: "https://class.imooc.com/api/jsonp".type: "get".async: true.dataType: "jsonp".jsonp: "jsonp".success: function (data) {
        console.log(data);
        // Data rendering
        renderDataToDom(data.slider)
    }
})
Copy the code