Front end and mobile development - Ajax programming - native JS code Ajax use, self encapsulating Ajax, form submission

Ajax programming

review

  1. What is network?

    Use network cable / wireless signal - various computers linked together to form a network

  2. What are resources?

    Data, strings, files, video, audio, etc. are stored on the computer.

  3. Server and client

    The client is responsible for browsing and using various resources (personal computer / personal mobile phone, etc.)

    The server is responsible for providing various data resources

  4. URL

    If the client wants to request resources, it needs to know where the resources are So the URL is a string of addresses that mark where the resource is (called uniform resource locator)

  5. IP

    The beginning of a URL that identifies the address of which computer on the network

  6. domain name

    ip is a string of It's hard to remember the four segmented numbers, so we have a domain name (a string of. Segmented English characters)

  7. DNS Service

    It is responsible for recording the correspondence between domain name and IP, which is used for the function of translating domain name into IP address, and looking for the IP of target computer in the network

  8. Request response process

    Client - > request - > server

    Client < - response < - server

  9. Classification of requests

    • Non Ajax - for example, open a web page and load all the data directly
    • Ajax request - is a way to request resources asynchronously (you can request data from the back end for a piece of the web page without refreshing the whole web page)
  10. Ajax request mode

    In the JS code, writing a piece of code can embed a request in the html web page and return the data to the place of the JS code

  11. core competencies

    Learn to analyze Network requests from the Network (the same as css / console printing)

  12. Request mode

    • GET - request data - is responsible for getting data from the background
    • POST - used to send data - send the data from the front end to the background
  13. Using Ajax

    $.ajax({

    type: '', / / request method - the default is get (both case and case are acceptable)

    url: '', / / the backend address of the request

    Data: {}, / / it can transfer data to the background

    success: function(res) {} / / fixed is a function question (used to accept the results returned in the background)

    })

  14. Back end interface

    Is the url used: only this url returns a string of string data instead of a web page

  15. Interface debugging tool

    • Don't write $ ajax can test whether the URL in the background is available
    • You can use the postman / REST Client plug-in to test whether the URL is available

4. Native JS code - Ajax usage

The Ajax function encapsulated by JQ was used before. In this lesson, let's take a look at the principle of internal implementation

4.0 JS - Ajax writing

// 1. Instantiate ajax objects
var ajaxObj = new XMLHttpRequest(); 

// 2. Register onreadystatechange event
/*
          The following events are triggered when the readyState state of the ajax object changes
          0 - ajax Object is created 
          1 - open Must be called
          2 - send Must be called
          3 - Receiving server data
          4 - Server data received
          When 0 changes to 1, the onreadystatechange event will be triggered once. When 1 to 2, 2 to 3, and 3 to 4, the onreadystatechange event will be triggered for execution
        */
// ajax(XMLHttpRequest) allows the browser to initiate a - > HTTP network request
ajaxObj.onreadystatechange = function () {
    // 4 (data reception completed) (JS code level), status stands for http network request success (200)
    if (ajaxObj.readyState === 4 && ajaxObj.status === 200) {
        // responseText retrieves the string data returned from the request
        var res = JSON.parse(ajaxObj.responseText);
        console.log(res);
    }
}

// 3. Call the open method to set the request method and the url address of the request
ajaxObj.open('GET', 'URL');

// 4. finally, call the send method to send the ajax request
ajaxObj.send();

readyState property and onreadystatechange event

Ajax starts from the creation of xhr objects until it completely receives the results returned by the server; We can divide the whole request response process into several stages.

Request phase asynchronous waiting phase response phase

  • The Ajax object - executing the send() method - enters the request sending phase
  • The browser starts the thread to request data at the specified URL. The background receives the request, executes the background code, and then returns the data
  • Ajax object - event listener receives the returned data and starts the event and callback function execution

4.1 JS - Ajax - GET request

  • Between the parameter and the previous interface address, use? separate
  • If there are multiple parameters, use & to separate them
  • There is no sequence requirement between multiple parameters

The request parameters spliced behind the url are strings in the format of "XXX = SSS & YYY = MMM & zzz = BBB", which is called query strings

// 1. Book information with ID 3
// 1.1 create Ajax object - binding state change event (prepare to accept the returned data)
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function () {
    if (ajax.readyState === 4 && ajax.status === 200) {
        var res = JSON.parse(ajax.responseText);
        console.log(res);
    }
}

// 1.2 set the request method, url and parameters of the request
ajax.open('GET', 'URL?id=3');
// 1.3 send request
ajax.send();


// 2. id is 1 and bookname is journey to the West
// 2.1 create another Ajax object
var ajaxObj = new XMLHttpRequest();
// 2.2 binding events
ajaxObj.onreadystatechange = function () {
    if (ajaxObj.readyState === 4 && ajaxObj.status === 200) {
        var res = JSON.parse(ajaxObj.responseText);
        console.log(res);
    }
}
// 2.3 setting request method - Request url - parameter splicing
ajaxObj.open('GET', 'URL?bookname=Journey to the West&id=1');
// 2.4 send request
ajaxObj.send();

4.2 url encoding

// Coding: the computer saves / transmits everything based on 0 and 1 bits. When we show it to us, we have to convert it into another form
// url encoding: convert the non English characters in the url address into another encoding form to ensure that the background accurately parses the parameters I pass through the url

// Method 1: fast encoding and decoding
console.log(encodeURI('Journey to the West&')); // %E8%A5%BF%E6%B8%B8%E8%AE%B0&
console.log(decodeURI('%E8%A5%BF%E6%B8%B8%E8%AE%B0&'));// Journey to the West& 

// Method 2: wider coding and decoding
console.log(encodeURIComponent('Journey to the West&')); // %E8%A5%BF%E6%B8%B8%E8%AE%B0%26
console.log(decodeURIComponent('%E8%A5%BF%E6%B8%B8%E8%AE%B0%26')); // Journey to the West&

// Method 2: more characters can be encoded
// Yes; /?: @ & = + $# Encode
// Neither of the two functions will be right -.! ~ * ' () coding

4.3 url encoding usage scenario

// Usage scenario:
// Question:
// We all know that the format of url transmission is key = value & key = value
// However, when my value also comes out &, the rule of parsing string is broken, and the background parsing fails

// 1.1 creating Ajax objects
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function () {
    if (ajax.readyState === 4 && ajax.status === 200) {
        var res = JSON.parse(ajax.responseText);
        console.log(res);
    }
}

// 1.2 set the request method, url and parameters of the request
ajax.open('GET', 'URL?a=6&10');
// 1.3 send request
ajax.send();

// Solution: url encoding
var str = encodeURIComponent("6&10");
console.log(str);
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function () {
    if (ajax.readyState === 4 && ajax.status === 200) {
        var res = JSON.parse(ajax.responseText);
        console.log(res);
    }
}

// 1.2 set the request method, url and parameters of the request
ajax.open('GET', `URL?a=${str}`);
// 1.3 send request
ajax.send();

4.4 JS - Ajax - POST request

Two differences between and GET requests

  • Different request parameter positions
  • One more request header is required
document.getElementById("createBtn").onclick = function () {
    // 1.1 creating Ajax objects - monitoring events
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
            var res = JSON.parse(this.responseText);
            console.log(res);
        }
    }
    // 1.2 setting request method - url of the request
    ajax.open('POST', 'URL');


    // //A request header must be added between open and send. The writing method of this request header is fixed. Can't remember to copy
    // 1.3 set request header - tell the backend what type of content I send you
    // It means that the parameter is passed to the background in the format of XXX = YYY & zzz = TTT. The background finds that the value is the following from the content type, and then parses the string according to the corresponding rules to extract the parameter name and value
    ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    // 1.4 send the request and carry the parameters in a fixed format
    // The data submitted by POST is still in the query string format, but the position has changed
    ajax.send('bookname=Red and black&author=Stendhal &publisher=French press&appkey=b7fc2560-5632-4da5-b625-58cff58c6b31');
}

4.5 practice

Exercise 1: Write native Ajax code - Please query public data(No need to bring appkey parameter), in id Data information for 2 (What data is this? What kind of request?)
        let ajaxObj = new XMLHttpRequest();
        ajaxObj.onreadystatechange = function(){
            if (ajaxObj.readyState == 4) {
                if (ajaxObj.status == 200) {
                    console.log(ajaxObj.responseText);
                }
            }
        }
        // Summary: multiple parameters need to be in? Followed by parameter name = value & parameter name = value
        ajaxObj.open("GET", "URL?id=2");
        ajaxObj.send();
Exercise 2: Write native Ajax code - Please check your watch(belt appkey And their own values), Add a piece of book information to the background, Then call the interface to query your own book information, Check whether it is added successfully - (This is to send data? What kind of request should be used?)
        // 1. Instantiate ajax objects
        let ajaxObj = new XMLHttpRequest();
        // 2. Binding events
        ajaxObj.onreadystatechange = function(){
            // 5. Accept the returned results
            if (ajaxObj.readyState == 4) {
                if (ajaxObj.status == 200) {
                    console.log(ajaxObj.responseText);
                }
            }
        }
        // 3. Set parameters
        ajaxObj.open("POST", "URL");

        // (New) - sets the type of content
        ajaxObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        // 4. Send request
        // (New) - the parameters of post should be written in send()
        ajaxObj.send("bookname=I am vscode Plug in books&author=vscode&publisher=121&appkey=b7fc2560-5632-4da5-b625-58cff58c6b31");

whole

  • Whether in GET or POST mode, if the request parameters have special characters, it is best to use urll encoding
  • The strings returned by the server are generally in JSON format. You need to call JSON yourself Parse conversion format
  • Which one to use, GET or POST, actually corresponds to the background regulations
  • The parameter name must also correspond to that specified in the background

5. Encapsulate Ajax yourself

To simulate the execution process of the code in the ajax function of JQ

		// function $(){};
        // $.ajax = function(){};
        // $.ajax();
        // Process steps of encapsulating functions:
        // 1. Define function shell (name)
        // 2. Call the function and pass in a set of examples (target)
        // 3. Write (paste + modify) the code in the function
        //   Figure out which variables will change in the future (pass a this time and b next time, then this variable must be on the formal parameter)

        function myAjax(obj) {
            // Deconstruction assignment extracts the value of the external parameter
            let { type, url, data, success } = obj;
            // Native Ajax
            let ajaxObj = new XMLHttpRequest();
            ajaxObj.onreadystatechange = function () {
                if (ajaxObj.readyState == 4) {
                    if (ajaxObj.status == 200) {
                        success(JSON.parse(ajaxObj.responseText)); // Callback the execution of the function corresponding to the success passed in from the outside and pass the value out
                    }
                }
            }
            ajaxObj.open(type, url);
            ajaxObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            // Convert object to string
            // You cannot use JSON Stringify, because the format of the string is wrong, we want the string of key = value & key = value
            var arr = [];  // Because there are many pairs of key=value in the object, I want to convert the object's unpaired key value into a string, and all the pairs are converted into a data structure (loaded with an array)
            for (var key in data) {
                arr.push(`${key}=${data[key]}`);
            }
            var argStr = arr.join("&"); // join is to use the symbol in () to link each value in the array to form a large string return
            ajaxObj.send(argStr);
        }
        myAjax({
            type: "POST",
            url: "http://123.57.109.30:3006/api/addbook",
            data: {
                bookname: "I am vscode Plug in books",
                author: "vscode",
                publisher: "ha-ha",
                appkey: "b7fc2560-5632-4da5-b625-58cff58c6b31"
            },
            success: function (res) {
                console.log(res);
            }
        })"
            },
            success: function (res) {
                console.log(res);
            }
        })

5.0 realize $ ajax() method

Recall $ What are the key attributes and functions of the configuration object passed in ajax

  • get method: pass parameter and not pass parameter
  • post mode: parameter transfer

Packaging ideas

  • Get the properties of the object (optional)
  • Basic Ajax code (write out the basic steps)
  • Judge the GET and POST requests and write the open and send methods respectively
  • Processing request parameters, processing parameters in the form of objects into query string format
  • When the ajax request succeeds, the success function is called to pass in the results returned by the server
  • Detail handling (default GET mode, case insensitive, etc.)

Use your own encapsulated Ajax methods

function $() { };
$.ajax = function (obj) {
    // 1. The default value ensures
    obj.type = obj.type || "GET"; // To prevent the type value from not being transmitted outside, the default value "GET" is given
    obj.type = obj.type.toUpperCase(); // Prevent the lower case passed outside, resulting in the following comparison inequality
    // Simulate the ajax implementation process of JQ - the XMLHTTPRequest of native JS is used internally

    // 2. Create a new Ajax object - binding event
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
            obj.success(JSON.parse(this.responseText)) // If the request succeeds, the callback function will execute and the value will be passed out
        }
    }
    // 3. Convert the parameters in the data object into this format key = value & key = value
    var arr = [];
    for (var prop in obj.data) {
        arr.push(`${prop}=${obj.data[prop]}`);
    }
    var argStr = arr.join("&"); // Splice string parameters

    // 4. Judge whether it is a GET method and whether there are parameters that conform to the splicing url? Chuan Shen
    if (obj.type == "GET") {
        obj.url += "?" + argStr; // Note that this must be + = Oh
    }
    // 5. Set Ajax request method and url
    ajax.open(obj.type, obj.url);

    // 6. If POST is judged, the content type of the request header must be set
    obj.type.toUpperCase() == "POST" && ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // If the type is determined to be POST mode, the content type of the request header must be set

    // 7. Initiate an Ajax request
    ajax.send(obj.type == "POST" ? argStr : '');
}
// Click query
document.getElementById("btn").onclick = function () {
    $.ajax({
        url: 'http://123.57.109.30:3006/api/getbooks',
        data: {
            appkey: "b7fc2560-5632-4da5-b625-58cff58c6b31"
        },
        success: function (res) {
            console.log(res);
        }
    })
}

// Click Add
document.getElementById("createBtn").onclick = function(){
    $.ajax({
        type: "post",
        url: 'http://123.57.109.30:3006/api/addbook',
        data: {
            bookname: "Red black tree",
            author: "Algorithmic Yang",
            publisher: "Mathematics press",
            appkey: "b7fc2560-5632-4da5-b625-58cff58c6b31"
        },
        success: function (res) {
            console.log(res);
        }
    })
}

6. Submission of forms

In the past, when there was no Ajax, data was submitted to the background in one direction with tables

6.0 synchronous submission of forms (understand)

Click the < input type = "submit" > button or the button in the form tab to submit the form to the url specified by the action. This is the synchronous submission of forms.

Disadvantages of synchronous submission:

  • The page will jump and the user experience is poor
  • If the data in the form is filled in again, it may be lost

The action, method, enctype and target of the from tag are only useful when the form is submitted synchronously

  • action is where the form tag is submitted
  • method is the way the form tag submits data (GET default / POST /...)
  • enctype is the type of form values held by the submitted form tag (application / x-www-form-urlencoded by default)
  • target is the form tab. Submission is to open a new tab on the current web page

Use the submission method of the form tag

  • Form submission GET method - with parameters
  • Form submission POST mode - with parameters
  • Form submission POST method - parameter + file
<!-- Form submission GET mode - With parameters -->
<!-- name Is the parameter name specified in the background, The value is filled in by the user value Attribute value -->
<h2>Form submission - get mode</h2>
<form action="URL" target="_blank">
    <input type="text" name="appkey" placeholder="user appkey">
    <input type="submit" value="Click to get book information"> 
</form>

<!-- Form submission POST mode - With parameters -->
<h2>Form submission - post mode(String content)</h2>
<form action="URL" method="POST" target="_blank">
    <input type="text" name="bookname" placeholder="title">
    <input type="text" name="author" placeholder="author">
    <input type="text" name="publisher" placeholder="press">
    <input type="text" name="appkey" placeholder="user appkey">
    <input type="submit" value="Add a new book"> 
</form>

<!-- Form submission POST mode - parameter+file -->
<!-- If there are documents, It has to be enctype="multipart/form-data", Upload byte stream(Special file format) -->
<h2>Form submission - post mode(With file)</h2>
<form action="URL" method="POST" enctype="multipart/form-data" target="_blank">
    <span>Select the file to upload</span>
    <input type="file" name="img">
    <input type="text" name="username" placeholder="user name">
    <input type="submit" value="Transfer files and parameters to the background"> 
</form>

6.1 Ajax asynchronous submission form (key) - with file

Asynchronous commit

Use JS to submit form data.

usage method

  • Listen for form submission events
  • Block default behavior for form submission
  • Collect values for form items
    • It can be collected one by one
    • You can also use serializeArray or serialize to collect data
  • ajax submits data to the interface to complete the data submission

serializeArray and serialize methods provided in jQuery

  • These two methods are encapsulated by jQuery
  • Use requirements: each item in the form must have a name attribute; These two methods get the value according to the name attribute of each item in the form
  • Requirements for using with ajax: name attribute value of each item in the form = = = parameters required by the interface
  • These two methods cannot collect the files selected in the file domain. That is, file upload cannot be realized
  • These two methods can collect the values of hidden fields
  • If an input box is disabled, it is disabled; Values cannot be collected through these two methods.
// Instead of submitting by default, use Ajax to submit
// (1): form tag - submit submit event
// (2) : button / input - click click event (triggered submission behavior) - default behavior of blocking clicks (submission behavior will be blocked)
// 1. GET parameter transfer - form
$("#formOne input[type=submit]").on("click", function (ev) {
    ev.preventDefault();
    $.ajax({
        type: "GET",
        url: "URL",
        data: {
            appkey: $("#appk").val()
        },
        success(res) {
            console.log(res);
        }
    })
})

// 2. POST parameter transfer - form - without file
$("#formTwo input[type=submit]").on("click", function (ev) {
    ev.preventDefault();
    var s = $("#formTwo").serializeArray(); / / set the object format in the array
    var s2 = $("#formTwo").serialize(); / / this is the format of string key = value & key = value
    $.ajax({
        type: "POST",
        url: "URL",
        data: s2,
        success(res) {
            console.log(res);
        }
    })
})

// 3. POST parameter transfer - form - with file
$("#formThree input[type=submit]").on("click", function (ev) {
    ev.preventDefault();
    var files = $('#theFile')[0].files; //  Get file type object
    if (files.length <= 0) { // Determine whether the file exists
        return alert('Please select a file before uploading!')
    }

    var fd = new FormData() // Form data - if there is a file, this data format must be used to transfer data
    fd.append('avatar123', files[0]);
    fd.append("username", $("#uname").val());

    $.ajax({
        method: 'POST',
        url: 'URL',
        data: fd,
        // You don't need to convert data to string to upload files
        // Do not convert to string key = value & key = value & key = value format
        processData: false,
        // Prevent JQ from operating on content types and upload directly in binary stream mode (multipart / form data is guaranteed)
        contentType: false,
        success: function (res) {
            console.log(res)
        }
    })
})


// Summary:
// JQ provides method $("form tag") serialize() collects the value of each name attribute and value in the tag, and then returns a string

7. Cases - Comments

7.0 - Case - Comment - initialization list

// 1.0 declaration variable - defines the method to obtain the comment data of the current page
var nowPage = 1; // What page of data do you currently want
var allPage; // How many pages are there
// Get comments area 1.1
function getCommentList() {
    // 1.2 calling the interface - passing the corresponding parameters to the background - obtaining data
    $.ajax({
        method: 'GET',
        url: `URL?page=${nowPage}&appkey=b7fc2560-5632-4da5-b625-58cff58c6b31`,
        success: function (res) {
            // 1.3 judgment is not 200 proof error - prompt message
            if (res.status !== 200) return alert(res.msg)
            // 1.4 how many pages are currently saved
            allPage = res.allPage;

            // 1.5 clear the current list page first - re lay
            $('#cmt-list').empty();
            // 1.6 data obtained this time
            $(res.data).each(function (i, item) {
                $('#cmt-list').append($(`<li class="list-group-item">
<span class="badge del" style="cursor:pointer" theid=${item.id}>delete</span> 
<span class="badge" style="background-color: #F0AD4E; "> comment time: ${item. Time}</span>
<span class="badge" style="background-color: #5BC0DE; "> commented by ${item. Username}</span>
${item.content}</li>`));
            })

            // 1.7 setting page number
            $("#pageShow").html(nowPage);
        }
    })
}

// 1.8 get the data of this page
getCommentList();

// 1.9 bind previous button / next button click event
$("#last").on("click", function () {
    if (nowPage > 1) nowPage--;
    getCommentList()
})
$("#next").on("click", function () {
    if (nowPage < allPage) nowPage++;
    getCommentList()
})

7.1 - cases - Comments - New comments

// 2.0 Click to publish events
$(function () {
    $('#formAddCmt').submit(function (e) {
        e.preventDefault()
        // 2.1 get the content on the form to form a key = value & key = value string
        var data = $(this).serialize()
        // 2.2 splicing my authorization code
        data += "&appkey=b7fc2560-5632-4da5-b625-58cff58c6b31";
        // 2.3 post sending data to the background
        $.post('URL', data, function (res) {
            if (res.status !== 201) {
                return alert('Failed to comment!' + res.msg);
            }
            // 2.4 after sending successfully, re acquire the data page
            nowPage = 1;
            getCommentList();
            // 2.5 reset form input box
            $('#formAddCmt')[0].reset()
        })
    })
})

7.2 - Case - Comment - delete comment

// 3.0 event delegation - to all delete binding click events
$("#cmt-list").on("click", ".del", function () {
    // 3.1 go to the above to bind the corresponding id of the deleted tag data, and click to obtain the unique id corresponding to the comment
    var theId = $(this).attr("theid");
    // 3.2 call the delete interface - let the background delete this data
    $.ajax({
        method: 'GET',
        url: `URL?id=${theId}&appkey=b7fc2560-5632-4da5-b625-58cff58c6b31`,
        success: function (res) {
            // 3.3 if it is not 200 status code, it means that the deletion fails. Give a prompt to prevent the code from continuing
            if (res.status !== 200) return alert(res.msg);
            // 3.4 if the above if can't get in, go here and save the current maximum page number (because the current page has no data, it will automatically go back to the previous page)
            allPage = res.allPage;
            if (nowPage > allPage) nowPage = allPage;
            // 3.5 set page number - retrieve data - lay current page
            getCommentList();
        }
    })
})

If there are deficiencies, please give more advice,
To be continued, keep updating!
Let's make progress together!

Tags: Javascript Front-end Ajax

Posted by mwd2005 on Mon, 02 May 2022 06:26:08 +0300