Reverse crawler 24 JQuery and Ajax
I Closure supplement
In the previous section, it was said that the closure function transmits information outward through return. In fact, there is another way to transmit information outward without return. Create a window global variable inside the function, assign the value of the local variable to it, and get its value outside the function.
function fn(){ let name = "wusir"; console.log(name); // Window object - > global variable (nnnn) // Create a global variable - > pass some information to the outside world in the closure function window.nnnn = name; } fn() console.log(nnnn);
II JS and HTML interaction
2.1 triggering JS code by event
In HTML, you can directly give the trigger of some events on the tag, for example, a button on the page
<input type="button" value="I love you when you order"/>
We can know that a button will be generated in the page at this time, but no matter how the button is clicked, it will not trigger any event. But at this time, I want to tell you that others actually triggered it, but you didn't deal with it. When we click the button, the browser actually collects click events, But because we didn't give anything about what to do when a click event happened. Therefore, there is no response. We can add what to do to the click event through the onclick attribute
<input type='button' value="I love you when you order" onclick="fn()" />
See, there are multiple onclick s, which means that when a click event occurs, execute fn(), fn(). What is fn()? FN is a function of javascript
Complete code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> function fn(){ alert("you've got such a nerve") } </script> </head> <body> <input type="button" value="I love you when you order" onclick="fn()"> </body> </html>
It's effective. We found it. At this point, we succeeded in realizing the way to call JS from HTML.
So how many events can be triggered in HTML? There are so many... So many that it's heinous. Let's just remember a few. The events in HTML can be viewed in the Event Listener Breakpoints on the far right of the Sources page of browser F12
click Click event focus Get focus blur Lose focus submit Submit Form change Replacement options scroll Scroll bar scroll mouseover Mouse over mouseout Mouse out mousemove Mouse sliding
The above is the first scheme to bind events. You can directly use onxxx series attributes in HTML tags to bind events. It's too easy to know which function the button binds at a glance in reverse. Therefore, JS also provides the following event binding scheme:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> // Because html code is loaded from top to bottom, if you don't use window Onload will cause the btn button not to be loaded after the js code is executed, resulting in event binding failure window.onload = function () { let btn = document.getElementById("btn"); // Get the page element (tag) through the value of id btn.addEventListener("click", function () { // Add functionality for event click console.log("I was ordered!") }) } </script> </head> <body> <input type="button" id="btn" value="Button"> </body> </html>
Now I want to change the content in the HTML after clicking the button
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> // Because html code is loaded from top to bottom, if you don't use window Onload will cause the btn button not to be loaded after the js code is executed, resulting in event binding failure window.onload = function () { let btn = document.getElementById("btn"); // Get the page element (tag) through the value of id btn.addEventListener("click", function () { // Add functionality for event click // Output some text to div document.getElementById("mydiv").innerText = "Do you love me??" }) } </script> </head> <body> <input type="button" id="btn" value="Button"> <div id="mydiv" style="width: 100px; height: 100px; background: pink;"></div> </body> </html>
2.2JS realizes login verification
Then, we can now transfer from HTML to JS, and the content in HTML can be captured in JS. At this time, the corresponding form verification can also be completed.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> window.onload = function () { // The first method of binding events // document.getElementById("btn").addEventListener("click", function () {}) // The second method of binding time document.getElementById("btn").onclick = function () { // The first way to get page elements let username = document.getElementById("username").value; let password = document.getElementById("password").value; // The second way to get page elements // let username = document.form.username.value; // let password = document.form.password.value; // The third way to get page elements // let username = document.querySelector("#username").value; // let password = document.querySelector("#password").value; let flag = true; if (!username) { document.getElementById("username_info").innerText = "User name cannot be empty"; flag = false; } if (!password) { document.getElementById("password_info").innerText = "Password cannot be empty"; flag = false; } if (flag) { document.getElementById("login_form").submit(); } } } </script> </head> <body> <form id="login_form" action="https://www.baidu.com" name="form"> <label for="username">user name: </label><input type="text" name="username" id="username"><span id="username_info"></span><br> <label for="password">password: </label><input type="text" name="password" id="password"><span id="password_info"></span><br> <input type="button" id="btn" value="Click me to log in"> </form> </body> </html>
Have you noticed that inadvertently, we can change the content in HTML through JS.
III jQuery
jQuery is a third-party library of Javascript that was once popular all over the country. jQuery's concept: write less do more, which means to free the front-end programmer from the cumbersome js code. Let's see if we can really free it.
About the version of jQuery: it is necessary to say here that jQuery has proposed three major versions, namely 1.1 x,2.x and 3 x. Note here that although the latest is 3 x. But all companies have chosen 1 x. Description jquery1 X has a very, very high position in the programming world, and in terms of its execution efficiency, code compatibility and code reliability, 1 X is really the best, so the version we study is naturally 1 X, we choose the same version as Tencent classroom, 1.9
It is recommended to download jQuery directly from cdn. Its essence is a js file, which is the same everywhere.
cdn website: https://www.bootcdn.cn/jquery/1.9.1/
CDN download jQuery website: https://cdn.bootcdn.net/ajax/libs/jquery/1.9.1/jquery.js
Just copy the URL downloaded from jquery to the browser and save it (ctrl+s) as a js file
3.1 initial use of jquery
We use jQuery to complete the basic click effect of a button. Of course, we have to compare it with traditional JS
Requirements: realize the function of button triggering console output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="jquery.js"></script> <script> // $is the hallmark of jquery // window.onload = function() {} / / it will not be executed until the entire page is loaded // When the page is loaded (no matter the picture is loaded, as long as the structure is loaded), it starts to execute // $(document).ready(function () { // console.log("I love you!"); // }) // After the page is loaded, execute it directly, which is equivalent to the above $(function () { // The way native js binds events is too cumbersome // document.querySelector("#btn").addEventListener("click", function () { // console.log("I love you!"); // }) // Selector of jquery, document querySelector("#btn") $("#btn").click(function () { // write less do more console.log("Do you believe it?"); }) }) </script> </head> <body> <input type="button" id="btn" value="Do you love me??"> </body> </html>
Except $, everything else seems easy to understand, and the code is concise and extremely comfortable.
What the hell is $? In jQuery, $can be regarded as the most obvious sign of jQuery, $() can convert an ordinary js object into a jQuery object, and in jQuery, $means jQuery.
3.2 jQuery realizes login verification
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery.js"></script> <script> $(function () { $(".btn").click(function () { // At the next click To clear the prompt after the last click $(".info").text(""); // Clean up all contents in info let username = $("#Username "). Val(); / / val() extracts the value value / / two functions. Give the parameter, insert it in, or take it out if you don't give the parameter let password = $("#password").val(); let gender = $("input[type='radio']:checked").val(); let city = $("#city").val(); / / you can directly get the value of the selected option on the page let flag = true; if (!username) { $("#username_info").text(" user name cannot be empty! "); / / two functions. Give parameters, insert them in, or take them out if you don't give parameters flag = false; } if (!password) { $("#password_info").text(" password cannot be empty! "); / / two functions. Give parameters, insert them in, and take them out if you don't give parameters flag = false; } if (!gender) { $("#gender_info").text(" you must select gender! "); / / two functions. Give parameters, insert them in, or take them out if you don't give parameters flag = false; } if (!city) { $("#city_info").text(" you must select a city! "); / / two functions. Give parameters, put them in, or take them out if you don't give parameters flag = false; } if (flag) { $("#login_form").submit() } else { return; } }) }) </script> </head> <body> <form id="login_form" action="http://www.baidu.com"> <label for="username">user name: </label><input type="text" id="username" name="username"><span class="info" id="username_info"></span><br /> <label for="password">password: </label><input type="password" id="password" name="password"><span class="info" id="password_info"></span><br /> <label>Gender: </label> <input type="radio" id="gender_men" name="gender" value="men"><label for="gender_men">male</label> <input type="radio" id="gender_women" name="gender" value="women"><label for="gender_women">female</label> <span class="info" id="gender_info"></span> <br /> <label for="city">city: </label> <select id="city" name="city"> <option value="">Please select</option> <option value="bj">Beijing</option> <option value="sh">Shanghai</option> <option value="gz">Guangzhou</option> <option value="sz">Shenzhen</option> </select> <span class="info" id="city_info"></span> <br /> <input type="button" class="btn" value="Sign in"> </form> </body> </html>
3.3 attribute control
Requirements: set a button, a text box and a div label, fill in the content in the text box, and add the content in the text box to the div and wrap the line after pressing the button each time.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="jquery.js"></script> <script> $(function () { $(".btn").click(function () { let val = $(".myin").val(); // After obtaining the data, you can clear the wind text box $(".myin").val(""); // Merge the contents of the original div with the contents of the text box and throw it in // $(".mydiv"). text($(".mydiv"). text() + val); // Textanything inserted will be treated as text $(".mydiv").html($(".mydiv").html() + val + "<br/>"); // html stuff will be treated as html }) }) </script> </head> <body> <input type="button" class="btn" value="I have a surprise"> <input type="text" class="myin"> <div class="mydiv"></div> </body> </html>
Requirements: get CSS style, set CSS style, and change CSS style by clicking the button
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="jquery.js"></script> <script> $(function () { $(".btn").click(function () { let display = $(".mydiv").css("display"); // Get the value of a css Style if (display == "none") { $(".mydiv").css("display", "block"); // Set a css Style } else { $(".mydiv").css("display", "none"); } }) }) </script> </head> <body> <input type="button" class="btn" value="I have a surprise"> <input type="text" class="myin"> <div class="mydiv" style="width: 500px; height: 60px; background: pink; display: none;"></div> </body> </html>
Requirements: custom attribute setting and viewing
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="jquery.js"></script> <script> $(function () { $(".btn").click(function () { // attr() html attribute setting $(".myin").attr("abc", "jay"); // Set attribute value let src = $(".myin").attr("data-src"); // View attribute values console.log(src) // heheda }) }) </script> </head> <body> <input type="button" class="btn" value="I have a surprise"> <input type="text" class="myin" data-src="heheda"> <div class="mydiv" style="width: 500px; height: 60px; background: pink; display: none;"></div> </body> </html>
3.4 traverser
each(function(i, data) {})
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="jquery.js"></script> <script> $(function () { // let txt = $("ul li").text(); // console.log(txt); $("ul li").each(function (i, data) { // i is the index and data is the dom object // console.log(this); // The default this is the dom object in js, which is equivalent to document What getelementbyid () got // Turn dom into jquery object // let txt = $(this).text(); // console.log(txt); console.log(i); console.log($(data).text()); }) }) </script> </head> <body> <ul> <li>Refrigerator</li> <li>Washing machine</li> <li>Flashlight</li> <li>radio</li> </ul> </body> </html>
IV Send ajax request
First of all, we use flash to create a background server (we made our own website)
Directory structure:
Server
from flask import Flask, render_template, request # pip install Flask app = Flask(__name__) @app.route("/") def index(): # Jump to home page print("Have you ever been to the server") name = "alex" # The data is rendered here and the html of a client is returned return render_template("index.html", name=name) if __name__ == '__main__': app.run()
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="/static/js/jquery.js"></script> </head> <body> I am a traditional html page, My name is{{name}} </body>
4.1 send get request
next. We use jquery to send ajax
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="/static/js/jquery.js"></script> <script> function setCookie(name, value) { let Days = 30; let exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString(); } $(function(){ // cookie information can be set anywhere in js setCookie("name", "i-have-a-dream") $(".get_btn").click(function(){ $.ajax({ url:"/ajax_get", // Server address: domain name + url method:'get', // Send get request headers:{ // Add request header information "token":"mememmememe", }, data:{ // Transfer parameters name:'alex', _: new Date().getTime() }, contentType:'application/json;charset=utf8', beforeSend: function(req){ // You can also add request header information in this way req.setRequestHeader("tokken", "i-can-do-it-haha"); }, success: function(back){ // After the request is successful The data is returned What are you doing? console.log(back); } }); }) }) </script> </head> <body> I am a traditional html page, My name is{{name}} <br/> <input type="button" class="get_btn" value="Click me to send get_request"> <hr/> <a href="javascript:void(0);" class="post_btn" >Click me to send post_request</a> </body> </html>
Server handling ajax_get request
@app.route("/ajax_get") def ajax_get_req(): # Receive information from cookie s n = request.cookies.get('name') if not n: return "No, cookie Don't come." # Receive information in header token = request.headers.get('token') if not token: return "no token Still want to come?" # Parameters of the get request received by Flask name = request.args.get('name') _ = request.args.get('_') if name and _: # Return json return {"name":'alex', "id": 10086, "isMen": True} else: return "Go home"
4.2 send post request (json)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="/static/js/jquery.js"></script> <style> #mask{ position:fixed; top:0; left:0; right:0; bottom: 0; background-color: rgba(0,0,0, .3); color: #fff; font-size:30px; text-align: center; padding-top:300px; display:none; } </style> <script> $(function(){ $(".post_btn").click(function(){ $('#mask').css("display","block"); $("#data_tbody").remove(); $.ajax({ url:'/ajax_post', method:'post', data: JSON.stringify({ name:'alex', id:'10086' }), headers: { // Send json data Change this header, or the server will not receive data "Content-Type": "application/json;charset=utf-8" }, dataType:"text", success:function(d){ $('#mask').css("display","none"); // Set no mask let data = JSON.parse(d); let tbody = $("<tbody id='data_tbody'></tbody>") data.forEach(function(item){ let tr = `<tr><td>${item.id}</td><td>${item.name}</td><td>${item.age}</td></tr>`; tbody.append(tr); }); $('table').append(tbody); } }) }); }) </script> </head> <body> I am a traditional html page, My name is{{name}} <br/> <input type="button" class="get_btn" value="Click me to send get_request"> <hr/> <a href="javascript:void(0);" class="post_btn" >Click me to send post_request_Try loading a table</a> <hr/> <table width="80%" border="1"> <thead> <tr> <td>id</td> <td>name</td> <td>age</td> </tr> </thead> </table> <div id="mask"><span>Loading......</span></div> </body> </html>
python server:
from flask import Flask, render_template, request # pip install Flask import time import json app = Flask(__name__) @app.route("/") def index(): # Jump to home page print("Have you ever been to the server") name = "alex" return render_template("index.html", name=name) # The data is rendered here and the html of a client is returned @app.route("/ajax_post", methods=['POST']) def ajax_get_post(): # time.sleep(3) # Receive JSON data print(request.json) lst = [ {"id": 1, "name": "Fei Zhang", "age": 16}, {"id": 2, "name": "Sun Bin", "age": 16}, {"id": 3, "name": "woodcutter", "age": 16}, {"id": 4, "name": "mogul", "age": 16}, ] return json.dumps(lst) if __name__ == '__main__': app.run()