A GET request

A GET request is typically used to GET information. Instead of a request body, it uses a URL to pass parameters (i.e., data to the background).

How to pass parameters:

  1. Common URL encoding is performed for the data to be sent (with names and values), that is, pairs of “name=value “(called: name/value pairs), with “&” concatenated between each pair, for example, “name= Value&name =value&… & name = value “;
  2. Since the name/value pair is appended to the URL address, you need to add a “?” at the beginning of the string of character arguments. , indicates the start of URL query parameters.
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tryrun 10</title>
</head>
<body>
    <div id="form">
        <label for="country">Countries:<input type="text" name="country" id="country"></label>
        <label for="city">City:<input type="text" name="city" id="city"></label>
    </div>
    <hr>
    <div>The country you are inquiring about is:<span id="ipt_country"></span></div>
    <div>The city you query is:<span id="ipt_city"></span></div>
    <br>
    <button type="button" id="search">The query</button>(The value you entered will be displayed at the top after the query is successful)<script>
        var oSearch = document.getElementById("search"),
            oIpt_country = document.getElementById("ipt_country"),
            oIpt_city = document.getElementById("ipt_city");

        var url = "/statics/demosource/demo_get_json.php";

        oSearch.onclick = function () {
            var country = document.getElementById("country").value,
                city = document.getElementById("city").value;

            var query = "country=" + country + "&city=" + city;

            var queryURL = url + "?" + query;

            // Initiate a GET request
            ajaxGet(queryURL);
        }

        function ajaxGet (url) {
            var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
                        var res = JSON.parse(xhr.responseText);
                        oIpt_country.innerText = res.params.country;
                        oIpt_city.innerText = res.params.city;
                    }
                }
            }
            
            xhr.open("GET", url);
            xhr.send();
        }
    </script>
</body>
Copy the code

The cache problem

For GET requests, the result of the request is cached by the browser, especially Internet Explorer. In this case, if the URL of the GET request does not change, the result of the request is the browser’s cache (that is, the result of the last GET request).

The solution

Change the URL of the GET request in real time. As long as the URL is different, the browser’s cached result is not fetched.

Add a timestamp parameter to the end of the URL. Because the timestamp can be accurate to milliseconds, it ensures that the time of each GET request is different and the request URL can be changed in real time.

var url = "/statics/demosource/demo_get_json.php";

// Append the timestamp parameter t to the end of the request parameter
var query = "user=" + user + "&pwd=" + pwd + "&t=" + new Date().getTime();

var queryURL = url + "?" + query;
// ajax_get encapsulates a request object for itself, not a fixed usage
ajax_get(queryURL);
Copy the code

Encapsulate the GET asynchronous request function

Steps:

  1. Instantiate an XMLHttpRequest object, which should be compatible if you are using IE7 or later;

  2. Perform normal URL encoding on the data data, or you can use the urlencodeData utility function provided in the preset code;

  3. Call the open() method to specify the request mode, request address, and whether the request is asynchronous. Note that the request address must be the result of concatenating the URL and request parameters.

  4. Call the send() method;

  5. Add a readyStatechange event handler to the XMLHttpRequest instance:

    • In the bestopen()Implemented before method callreadystatechangeEvent, more rigorous;
    • In the event handler to judge the HTTP request status, only when the request status is “completed”, can ensure the complete response content;
  6. Based on the HTTP status code (that is, the value of the status attribute), the corresponding callback function is executed:

    • HTTP status codes between 200 and 300 (excluding 300) or 304 are successful: yesJSON.parse()Method will beresponseTextProperty values are parsed into JavaScript objects and treated assuccessFunction argument outgoing;
    • If the HTTP status code is any other value, the request failed: callerrorFunction and passes the failed HTTP status code as an argument;
  7. An ajaxPost wrapped in the results section can respond properly.

    • The 403: GET request URL is incorrecturlConcatenated “?” with the request parameter. .
<html>
<head>
    <meta charset="UTF-8">
    <script>
        function ajaxGet (url, data, success, error) {
            // Start your code below
            var xhr = window.XMLHttpRequest ? new 				window.XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
            data = urlencodeData (data)
            console.log(data);
            xhr.onreadystatechange = function(){
                if(xhr.readyState ! = =4) return;
                if(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {console.log(xhr.status);
                    var res = JSON.parse(xhr.responseText)
                        success(res);
                }else{
                    var res = JSON.parse(xhr.responseText)
                    console.log(res); error(res); }}; url = url +'? ' + data;
            xhr.open('GET',url,true);
            xhr.send(null);
            }
         
    </script>
    
    
    <! -- Tool functions -->
    <script>
        // Used to perform normal URL encoding on JavaScript objects
        // The encoded format is: "Name = value &... & Name = value"
        function urlencodeData (data) {
            if(! data)return;
            var pairs = [];
            for (var name in data) {
                if(! data.hasOwnProperty(name))continue;
                if (typeof data[name] === "function") continue;
                var value = (data[name] === null || data[name] === undefined)?"" : data[name].toString();
                pairs.push(encodeURIComponent(name) + "=" + encodeURIComponent(value));
            }
            return pairs.join("&");
        }
    </script>
    
    <! Here is the test code -->
    <! Test the CSS part of the code -->
    <style>
        #request { text-align: center; }
        .request-result { padding: 12px; border: 1px solid #e8e8e8; 			border-radius: 2px; box-shadow: 0 1px 3px 1px #d9dfe9; }
        .request-btn { margin-top: 12px; padding: 7px; color: #fff; 			border-radius: 7px; transition: all .2s; cursor: pointer; }
        .request-success { background-color: #1890ff; }
        .request-success:hover { background-color: #40a9ff; }
        .request-error { background-color: #d9363e; }
        .request-error:hover { background-color: #ff7875; }
    </style>
</head>
<body>
    <! Test the HTML part of the code -->
    <div id="request">
        <div class="request-result">
            <div class="res-tip">Test if the asynchronous GET request you encapsulate rings properly</div>
            <div class="res-param"></div>
        </div>
        <div class="request-btn request-success">A test of a successful request</div>
        <div class="request-btn request-error">Tests for failed requests</div>
    </div>
    
    <! Test the js part of the code -->
    <script>
        var oDivs = document.getElementsByTagName("div");
        var oResult_tip = oDivs[2],
            oResult_param = oDivs[3],
            oSuccess = oDivs[4],
            oError = oDivs[5];
            
        var url = "/statics/demosource/demo_get_json.php",
            badUrl = "/statics/demosource/404.txt";
        var data = {
                aa:null.from: "Nanchang".to: "Xiamen".time: "Today"
            };
        var success = function (res) {
            oResult_tip.innerText = "Request successful";
            oResult_param.innerHTML = "
       
+ res.params.from + "
+ res.params.to + "
+ res.params.time + "</span></div>"; }; var error = function (res) { oResult_tip.innerText = "Request failed:" + res; oResult_param.innerHTML = ""; }; oSuccess.onclick = function () { ajaxGet(url, data, success, error); }; oError.onclick = function () { ajaxGet(badUrl, data, success, error); }
</script> </body> </html> Copy the code

A POST request

A POST request is typically used to modify a resource on a server by sending a request body in which the data passed by the client to the server is contained.

The “Content-Type” request header is used to set the encoding format of the request body.

Form-encoded POST requests

Key steps in a POST request to send data using form encoding:

  1. Performs normal URL encoding on the data that needs to be sent (with names and values), that is, concatenated as a name/value pair like a GET request;
  2. will"Content-Type"The value of the request header is set to"application/x-www-form-urlencoded".
// Get the form data entered by the user
var country = document.getElementById("country").value,
    city = document.getElementById("city").value;

// Concatenate data into name/value pairs
var query = "country=" + country + "&city=" + city;

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    / /... . Omit the event handler
}

// Specify a POST request
xhr.open("POST"."/statics/demosource/demo_post_json.php");

// Sets the encoding method for the request body
xhr.setRequestHeader("Content-Type"."application/x-www-form-urlencoded");

// Send the request body (data)
xhr.send(query);
Copy the code

Json-encoded POST request

JSON is a lightweight back and forth data exchange format that can be encoded using the jSON.stringify native API, which is much faster than form encoding.

Key steps in a POST request to send data in jSON-encoded form:

  1. "Content-Type"The request header value needs to be"application/json";
  2. Serialize the request body, available in JavaScriptJSON.stringifyComplete this step.
// Get the form data entered by the user
var country = document.getElementById("country").value,
    city = document.getElementById("city").value;

// Convert data to JavaScript objects
var data = {
    country : country,
    city : city
}

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    / /... . Omit the event handler
}

// Specify a POST request
xhr.open("PO ST"."/statics/demosource/demo_json_data.php");

// Sets the encoding method for the request body
xhr.setRequestHeader("Content-Type"."application/json");

// Encode the request body and send it
xhr.send(JSON.stringify(data));
Copy the code

A comparison of the two approaches

GET request:

  1. Used generally of information.To obtain: To retrieve a resource on a server by sending a request
  2. The data is contained in the URL address;
  3. The amount of data is limited by the length of the URL;
  4. Unsafe: the URL of the browservisibleTo, plaintext transmission;
  5. A GET requestWill be cached;
  6. GET has no request body and requests are relatively fast.

POST request:

  1. Commonly used inModify theResources on the server: Submitting data to a specified resource, the back-end processing of the request often causes the server to create new resources or modify existing resources;
  2. The data is contained in the request body;
  3. There is no data limit, can be limited in the server configuration;
  4. It can only be better than GETsecurityIn fact, it is not secure: it can be seen through developer tools or packet capture, plaintext transmission;
  5. A POST requestDon't cache;
  6. POST is relatively stable and reliable: it can send content containing unknown characters.

Easy mistakes: HTTP protocol does not limit the length of GET and POST, the maximum length of GET is because browsers and Web servers limit the length of THE URL, different browsers and Web servers limit the maximum length, they limit the length of the entire URL. Not just the data length of the query parameter.

Ajax extensions

In the jQuery Ajax

JQuery is a JavaScript library that encapsulates common JavaScript functionality, including Ajax, which we just learned about.

Common Ajax requests in jQuery include the following:

  • $.ajax(url, options)
  • $.get(url, data, callback, dataType)
  • $.post(url, data, callback, dataType)
  • $.getJSON(url, data, callback)
  • $.getScript(url, callback)
  • JQuery elements.load(url, data, callback)
// Use jQuery to initiate ajax requests
$.ajax("/statics/demosource/demo_get_json.php", {
    // Request type
    type: "GET".// The data to send
    data: {
        country: country,
        city: city
    },
    // Data format
    dataType: "json".// The request is executed after success
    success: function (res) {    // res is the data returned for the successful response
        oIpt_country.innerText = res.params.country;
        oIpt_city.innerText = res.params.city;
    },
    // The request is executed after failure
    error: function (res) {    // Where res is the data returned by the response failure
        alert("Request failed:"+ res.status); }});Copy the code

Alternative to Ajax: Fetch

The Fetch API is a JavaScript native interface that evolved with ES6. Like Ajax, it allows developers to make HTTP requests asynchronously, but its more straightforward invocation, promise-based data processing is called an alternative to Ajax.

fetch("/statics/demosource/demo_json_data.php", {
    method: "POST".header: new Headers({"Content-Type" : "application/json"}),
    body: JSON.stringify(data)
})
.then(function (res) {
    return res.ok ? res.json() : Promise.reject(res);
})
.then(function (data) {
    oIpt_country.innerText = data.country;
    oIpt_city.innerText = data.city;
})
.catch(function (res) {
    alert("Request failed:" + res.status);
})
Copy the code

JSON

JSON = JavaScript Object Notation, which is a lightweight data interchange format.

Grammar rules

JSON syntax can represent three types of values:

  • Simple values: uses the same syntax as JavaScript and can be represented in JSONnumber,string,booleannullJSON does not support special values in JavaScriptundefined;
  • Object: As a complex data type, object represents a group of unordered key-value pairs. The values in each key-value pair can be simple values or values of complex data types.
  • Array: An array is also a complex data type that represents an ordered list of values. The values of an array can be of any type — simple values, objects, or arrays.

Simple values

//JSON indicates the value 7
7
//JSON indicates a character string
"JSON is a format for data exchange"
Copy the code

Note:

The biggest difference between JSON strings and JavaScript strings is that JSON strings must be quoted in double quotes, which can cause syntax errors.

object

Objects in JSON are slightly different from JavaScript object literals.

JavaScript object literals:

{
    name : "Alan".age : 21
}
Copy the code

Json representation

{
    "name" : "Alax"."age" : 21
}
Copy the code

The key (attribute name) of the JSON object must be in double quotes.

The property values of a JSON object can be simple or complex

{
    "name" : "Alan"."age" : 21."child" : {
        "name" : "Tim"."age" : 7}}Copy the code

An array of

JSON arrays take the form of array literals in JavaScript.

Array literals in JavaScript:

[21."Alan".false]
Copy the code

Json representation

[21."Alan".false]
Copy the code

conclusion

  1. JSON is a string representation of a JavaScript object, which uses plain text format to represent information about a JavaScript object, essentially a string;
  2. Objects and arrays are often used as the outermost form of JSON data structures, and they can be used to create a variety of data structures. Of course, this is not mandatory.

JavaScript built-in JSON object

ECMAScript 5 defines a native JSON object that serializes JavaScript objects into JSON strings or parses JSON strings into native JavaScript values.

JSON object methods:

  1. JSON.stringify(): used to serialize JavaScript objects and convert them to JSON strings;
  2. JSON.parse(): Used to parse JSON strings and convert them to JavaScript values.

Tip: JSON objects have no other function and cannot be used as constructors.

Stringify method

The json.stringify () method is used to convert a JavaScript value/object to a JSON string.

var obj = {
    name: "Alan".age: 21.child: {
        name: "Tim".age: 7}};// Serialize the obj object to a JSON formatted string
var json = JSON.stringify(obj)
Copy the code

The parse method

The json.parse () method is used to parse JSON data into native JavaScript values.

var json = '{"name":"Alan","age":21,"child":{"name":"Tim","age":7}}';

// JSON data is essentially a string and cannot be accessed directly to an attribute
console.log(json.name);    // undefined

// Parse json and convert it to a native JavaScript object
var obj = JSON.parse(json);
console.log(obj.name);    // You can use JavaScript methods to access a property
Copy the code