A template engine
What it does: Concatenates data with HTML using the template syntax provided by the template engine.
Aui.github. IO /art-templat…
Using the step
- Download the art-template template engine file and import the library file in the HTML page
<script src="./js/template-web.js"></script>
Copy the code
- Prepare the art-template template
<script id="tpl" type="text/html">
<div class="box"></div>
</script>
Copy the code
- Tells the template engine which template to concatenate with which data
var html = template('tpl', {username: 'zhangsan', age: '20'});
Copy the code
- Adds the concatenated HTML string to the page
document.getElementById('container').innerHTML = html;
Copy the code
- Using template syntax to tell the template engine how to concatenate data and HTML strings
<script id="tpl" type="text/html">
<div class="box"> {{ username }} </div>
</script>
Copy the code
Verify the uniqueness of email addresses
- Gets the text box and adds an out-of-focus event to it
- When out of focus, check whether the email address entered by the user matches the rule
- If it does not comply with the rules, the program is blocked and a message is displayed
- Send a request to the server to check whether the email address is registered by someone else
- Determines which prompt message to display on the client based on the value returned by the server
The content in the search box is automatically displayed
- Gets the search box and adds a user input event to it
- Gets the keyword entered by the user
- Send a request to the server side with the keyword as the request parameter
- Displays the response data at the bottom of the search box
Provincial and urban three-level linkage
- Obtain provincial information through the interface
- Use JavaScript to get the elements of the provincial drop-down box
- The province information returned by the server is displayed in the drop-down list box
- Add a form value change event (onchange) to the dropdown element
- When the user selects a province, the city information is obtained based on the province ID
- When the user selects a city, the county seat information is obtained based on the city ID
FormData
The FormData object
-
Emulating an HTML form is equivalent to mapping an HTML form to a form object and automatically stitching the data in the form object into the format of the request parameters.
-
Asynchronously upload binary files
-
Preparing HTML forms
<form id="form"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="button" /> </form>Copy the code
- Convert the HTML form to a formData object
var form = document.getElementById('form');
var formData = new FormData(form);
Copy the code
- Submit form object
xhr.send(formData);
Copy the code
Instance method of the FormData object
To the operation of the form of object data, in general form is not submitted directly to the server side, after users click on the submit button, the client often to check the form data, this requests us to obtain the form data of value, and to be able to check or reset to its, these actions depend on the FormData object provides some of the ways
- Gets the value of an attribute in the form object
formData.get('key');
Copy the code
- Sets the value of an attribute in the form object
- The property is overwritten if it already exists, or created if it does not
formData.set('key', 'value');
Copy the code
- Deletes the value of an attribute in the form object
formData.delete('key');
Copy the code
- Appends attribute values to the form object
formData.append('key', 'value');
Copy the code
Note: The difference between the set method and the Append method is that in the case of an existing attribute name, the set method overrides the value of the existing key name, and Append retains both values. (If the server side is not set in advance, the last value of the same attribute name is accepted by default)
- Baima is received here
FormData Binary file upload
<input type="file" id="file"/>
Copy the code
Var file = document.getelementById ('file') file.onchange = function () {var formData = new FormData(); Formdata.append ('attrName', this.files[0]); // Append the user's selected binary file to the form object. // To configure the Ajax object, the request must be post xhr.open('post', 'www.example.com'); xhr.send(formData); }Copy the code
FormData File upload progress display
File.onchange = function () {xhr.upload.onprogress = function (ev) {// When the user selects a file, the onprogress event xhr.upload.onprogress = function (ev) {// Width = (ev.loaded/ev.total) * 100 + '%'; bar.style.width = (ev.loaded/ev.total) * 100 + '%'; }}Copy the code
FormData File upload progress display
File.onchange = function () {xhr.upload.onprogress = function (ev) {// When the user selects a file, the onprogress event xhr.upload.onprogress = function (ev) {// Width = (ev.loaded/ev.total) * 100 + '%'; bar.style.width = (ev.loaded/ev.total) * 100 + '%'; }}Copy the code
FormData file upload image instant preview
After we upload the image to the server, the server usually passes the image address to the client as response data. The client can retrieve the image address from the response data and display the image on the page.
xhr.onload = function () { var result = JSON.parse(xhr.responseText); var img = document.createElement('img'); img.src = result.src; img.onload = function () { document.body.appendChild(this); }}Copy the code
The same-origin policy
Ajax request restrictions
Ajax can only send requests to its own server. For example, if there is A website A and A website B, the HTML file in website A can only send Ajax requests to the server of website A, and the HTML file in website B can only send Ajax requests to website B, but website A cannot send Ajax requests to website B. Similarly, Website B cannot send Ajax requests to website A.
- Request weather information
What is homology
If two pages have the same protocol, domain name, and port, they belong to the same source.
- www.example.com/dir/page.ht…The HTTP protocol,
www.example.com
Domain name, port 80 - www.example.com/dir2/other…. – the same
- Example.com/dir/other.h… — Different domain names vary from source to source
- V2.www.example.com/dir/other.h… — Different domain names vary from source to source
- www.example.com:81/dir/page.ht… — Ports vary according to the source
- www.example.com/dir/page.ht… — Different source, different protocol
Use JSONP to solve the homology restriction problem
Jsonp, which stands for JSON with Padding, is not an Ajax request, but it can simulate an Ajax request.
- Write the server-side request addresses of different sources in the SRC attribute of the script tag
< script SRC = "http://localhost:3001" > < / script > < script SRC = "https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js" > < / script >Copy the code
- The server-side response data must be a function call, and the actual data to be sent to the client needs to be the parameter of the function call
Const data = 'fn({name: "c ", age: "20"})'; res.send(data);Copy the code
- Define the function fn under the client global scope
function fn (data) { }
Copy the code
- The data returned by the server is processed inside the FN function
funciton fn (data) { console.log(data); }
Copy the code
Cross-domain server code
Const fnName = req.query.callback; Const data = json.stringify ({name: "zhangsan"}); // Return the corresponding calling code to the client const data = json.stringify ({name: "zhangsan"}); const result = fnName + `(${data})`; setTimeout(() => { res.send(result) }, 1000);Copy the code
- Use the jsonp() method
Cross-domain parameter transfer can be implemented directly on the server side through the jsonp() method.
res.jsonp({name: 'lisi', age: 20});
Copy the code
JSONP code optimization
- The client needs to pass the function name to the server
- Turn the sending of script requests into dynamic requests
- Encapsulate jSONP functions to facilitate request sending
- Optimize server-side code
CORS cross-domain resource sharing
Called cross-orifin Resource Sharing, CORS allows browsers to make Ajax requests to cross-domain servers, overcoming the restriction that Ajax can only be used homologous.
orgin: http://localhost:3000
Copy the code
Access-Control-Allow-Oringin: 'http://localhost:3000'
Access-Control-Allow-Oringin: '*'
Copy the code
Server-side solution for accessing non-homogeneous data
The same origin policy is a limitation imposed by the browser on Ajax technology; there is no such restriction on the server side.
The server-side developer can direct access to the same site, the data, so as the client, can make your own server to obtain the same site data, wait for your website server access to the data before the data the client response to their website, thus bypassing the browser’s same-origin policy restrictions.
Such as:
Use the client of no.1 website to visit the server side of no.1 website, and then the server side of no.1 website to get the data provided by the server side of no.2 website, and then respond to the obtained data to the client side of no.1 website
Got the module
NPM install
npm install got
Copy the code
Introducing the GLOBAL Offset Module
const got = require('got');
Copy the code
Using the GOT Module
(async () => {
try {
const response = await got('https://google.com');
console.log('statusCode:', response.statusCode);
console.log('body:', response.body);
} catch (error) {
console.log('error:', error);
}
})();
Copy the code
The res. Send (response. Body); This is a way to circumvent the browser’s same-origin policy by returning data corresponding to non-same-origin sites.
Cookies to review
The website application is divided into two parts: the server and the client. The client initiates the request and the server initiates the response. The communication between the two needs to follow the rules set in the HTTP protocol.
HTTP states that the communication between the server and the client is stateless. The server does not care who the client is, but only responds to the request. Once the response is over, the communication is over.
In the process of the current website interaction, the server side needs to identify the identity of the client, then you need to use cookie, cookie is used to realize the identity of the server side and the client side of a technology.
Cookie is equivalent to the ID card sent by the server to the client. When the client sends a request to the server for the first time, the server detects that the current client does not have a corresponding cookie, and the server responds to the cookie back to the client, so that the client will carry the cookie when sending a request again. Automatically sends it to the server, and the server knows who the client is. Cookies establish a persistent connection between the server and client.
WithCredentials attribute
When sending a cross-domain request using Ajax technology, cookie information is not carried in the request by default.
WithCredentials: Specifies whether cookie information is carried when cross-domain requests are involved. The default value is false
checkLogin.addEventListener('click', function () { let xhr = new XMLHttpRequest(); / / to the ajax object configured XHR. Open (' get 'and' http://localhost:3001/checkLogin '); // When sending a cross-domain request, carry cookie information xhr.withCredentials = true; // Send the Ajax request and pass the request parameter xhr.send(); Xhr.addeventlistener ('load', function() {console.log(xhr.responsetext); // Xhr.adDeventListener ('load', function() {console.log(xhr.responsetext); })})Copy the code
Access-control-allow-credentials: true Allows clients to send requests with cookies
app.use((req, res, next) => { // 1. Which clients are allowed to access me // * means that all clients are allowed to access me // header(' response header attribute name ',' response header attribute name corresponding value ') // Note: Header (' access-Control-allow-origin ', 'http://localhost:3000') // 2. Res. header(' access-Control-allow-methods ', 'get,post'); Header (' access-Control-allow-credentials ', true); // Allow clients to send cross-domain requests with cookie information res.header(' access-Control-allow-credentials ', true); next(); });Copy the code