Knowledge supplement
Base address configuration
- New baseAPi. Js
The ajaxPrefilter method registers a callback function
// This callback function is called before using jQ's asynchronous request method
// And pass the configuration object of jQ's request to Option
// In the callback function, you can get the url of the configuration object and add the base address to it
$.ajaxPrefilter(function(option) {
option.url = 'http://api-breakingnews-web.itheima.net' + option.url;
})
Copy the code
- In the login.html file, import baseapi.js before the login.js file
<script src="/assets/lib/jquery.js"></script> <! Import base address file --><script src="/assets/js/baseAPI.js"></script>
<script src="/assets/js/login.js"></script>
Copy the code
- In the login.js file, an Ajax request can be made without the base address in the URL
$.ajax({
method: 'post'.url: '/api/login'.data: data,
success: function(res) {}); }})Copy the code
1. Interaction principle of browser server
- IP: the unique identification (equivalent to a house number) of a computer on the Internet
- Port: the serial ID (equivalent to a person’s name) of a program on a computer that communicates with the network
1.1 Browser Server Interaction
1.2 Request Packets and Response Packets
1.2.1 Request Packets
1.2.2 Response Packets
1.3 the URL address
UniformResourceLocator UniformResourceLocator
2. ajax
Why ajax?
- Good user experience: because there is no need to refresh the entire page, it will not affect the user’s operation in the browser
- Saving resources: Because there is no need to refresh the entire page, saving network traffic and reducing the area and times of page redrawing
2.1 What is Ajax
Ajax stands for Asynchronous JavaScript And XML
Common sense: Ajax is the way to use XMLHttpRequest objects in web pages to interact with server data.
Outstanding features: the current page is not refreshed, no jump.
The $2.2. The get
$.get(url,[data],[callback])
The data requested by the browser is stored in the URL. The data responded by the server is stored in the response format. The format of the request packets sent by the browser and the packet parsed by the server comply with HTTP
- A request without parameters
2. The nature of the request with parameters is to add the second parameter object of the GET method to the URL as a key/value pair string. The back!
2.3 $. Post
$.post(url,[data],[callback])
A POST request is used to submit data – the data is sent to the server in the request form
2.3 $. Ajax
$.ajax() is more comprehensive and can both fetch and submit data
$.ajax({
type: 'GET'.url: 'http://www.liulongbin.top:3006/api/getbooks'.data: {
id: 1
},
success: function(res) {
console.log(res)
}
})
Copy the code
2.4 interface
When data is requested using Ajax, the REQUESTED URL is called a data interface. Also, each interface must have a request mode.
A method provided by the server side, we call the server method through the browser side
2.5 Prevent forms from being submitted by default
// Prevent the button from triggering the default submission of the form by default, because the form is submitted, the whole page will be re-rendered, resulting in page refresh
e.preventDefault();
Copy the code
3. The Form Form
Forms are mainly responsible for data collection functions in web pages.
3.1 Attributes of the Form Label
-
Action (Mailing address)
- Specifies where form data is sent when the form is submitted.
- Property: A URL provided by the back end that is responsible for receiving data submitted from the form.
- Is not specified
action
Property value empty,action
Is the default value for the current pageURL
address - When the form is submitted, it immediately jumps to
action
Property specifiedURL
address
-
target
target
Property to specify where to openaction URL
-
method
- Specifies how form data is submitted to the Action URL
- Get is a good way to submit small, simple data
- Post is suitable for submitting large, complex, or file uploads
-
enctype
- Provisions in theHow do YOU encode form data before sending it
3.2 Disadvantages of form submission
Disadvantages:
<form>
When the form is submitted synchronously, the entire page jumps,Jump to the address pointed to by the action URLThe user experience is poor<form>
After a form is submitted synchronously, the previous state and data of the page are lost
Solution: The form simply collects the data complex, and Ajax takes care of submitting the data to the server
3.3 Prevent default submission of forms
$('#f1').on('submit'.function(e) {
alert('Listening on form submission event 2')
e.preventDefault()
})
Copy the code
3.3 Obtaining form data jq.serialize()
** Note: ** When using the serialize() function to quickly retrieve form data, you must add the name attribute to each form element
<form action="/login" id="f1">
<input type="text" name="user_name" />
<input type="password" name="password" />
<button type="submit">submit</button>
</form>
$('#f1').on('submit'.function(e) {
// Block the default submission behavior of the form
e.preventDefault();
// Get the form data
let data = $(this).serialize();
console.log(data); // user_name= user name value &password Password value
})
Copy the code
3.4 dom.reset() Quickly clears the form text box
Note: reset() is a dom object method, so convert the Jq object to the DOM object $(‘#formAddCmt’)[0].reset()
$('#formAddCmt').on('submit'.function(e) {
// Block the default commit
e.preventDefault();
// Get the data for the form element
let data = $(this).serialize();
$.post('http://www.liulongbin.top:3006/api/addcmt', data, function(res) {
if(res.status ! =201) return alert('Failed to comment');
// Update the list
upload();
// Note the direction of this
// Automatically empties the text
$('#formAddCmt') [0].reset()
})
})
Copy the code
4. Template engines
Template engine, which can automatically generate a complete HTML page based on the template structure and data specified by the programmer
benefits
- Reduced string concatenation
- Make the code structure clearer
- Make code easier to read and maintain
4.1 art – the template
Official website to download
4.1.1 Procedure
-
Import the art – the template
<script src="./lib/template-web.js"></script> Copy the code
-
Preparing the HTML container
<div id="container"></div> Copy the code
-
Defining data Data
-
Define the template
<script type="text/html" id="tpl-user"> <h1>{{name}} ------ {{age}}</h1> </script> Copy the code
-
Calling the template function
var htmlStr = template('tpl-user', data) Copy the code
-
Render HTML structure
$('#container').html(htmlStr) Copy the code
The sample
<! Import template engine -->
<! -- In the window global, there is another function called template(' template Id', the data object to render) -->
<script src="./lib/template-web.js"></script>
<script src="./lib/jquery.js"></script>
</head>
<body>
<! Prepare the container -->
<div id="container"></div>
<! -- 3. Define template -->
<! 3.1 The HTML structure of the template must be defined in script
<! -- Notice that the type is HTML, this is a script tag, not executed as js -->
<script type="text/html" id="tpl-user"></script>
<script>
// Define a filter for processing time
template.defaults.imports.dateFormat = function(date) {
var y = date.getFullYear()
var m = date.getMonth() + 1
var d = date.getDate()
return y + The '-' + m + The '-' + d
}
// 2. Define the data to render
var data = {
name: 'zs'.age: 20.test: Test text output
.flag: 1.hobby: ['eat'.'sleep'.'Write code'].regTime: new Date()}// 4. Call template
var htmlStr = template('tpl-user', data)
console.log(htmlStr);
// 5. Render the HTML structure and put it in the HTML container
$('#container').html(htmlStr)
</script>
</body>
</html>
Copy the code
4.1.2 Standard Syntax
- The original output
// If HTML tags are included, ensure that the HTML tags are rendered properly
{{@ value}}
Copy the code
- Conditions of the output
{{if v1}}
...
{{else if v2}}
...
{{/if}}
Copy the code
- Loop output
{{each arr}} < li > index is: {{$index}}, circulation is: {{$value}} < / li > {{/ each}}Copy the code
- The filter
Example – Formatting time filters
-
Define the data
var data = { regTime: new Date()}Copy the code
-
Defining filters
// Define a filter for processing time template.defaults.imports.dateFormat = function (date) { var y = date.getFullYear() var m = date.getMonth() + 1 var d = date.getDate() return y + The '-' + m + The '-' + d } Copy the code
-
Use filters in the template engine
<script type="text/html" id="tpl-user"></script> Copy the code
4.2 Implementation principle of template Engine
- Extract the desired string with exec()
var str = '< div > I am {{name}} < / div >'
// The contents of the regular expression () represent a grouping, in order to extract "name"
var pattern = /{{([a-zA-Z]+)}}/
var result = pattern.exec(str)
console.log(result)
Copy the code
- Then through the loop, the extracted attribute name (such as name) is extracted one by one to get the corresponding attribute value from data
data[patternResult[1]]
And should beStr.replace (' replaced value ', 'replaced value ')
In the label
var data = { name: 'Joe'.age: 20 }
var str = '
{{name}} year {{age}} year
'
// \s-- matches the space >=0
var pattern = /{{\s*([a-zA-Z]+)\s*}}/
var patternResult = null
while (patternResult = pattern.exec(str)) {
str = str.replace(patternResult[0], data[patternResult[1]])}console.log(str)
Copy the code
4.3 Customize simple template engine
/template.js/
function template(id, data) {
var str = document.getElementById(id).innerHTML
var pattern = /{{\s*([a-zA-Z]+)\s*}}/
var pattResult = null
while (pattResult = pattern.exec(str)) {
str = str.replace(pattResult[0], data[pattResult[1]])}return str
}
Copy the code
/ Call your template engine. HTML /
<script src="./js/template.js"></script>
</head>
<body>
<div id="user-box"></div>
<script type="text/html" id="tpl-user"></script>
<script>
// Define data
var data = { name: 'zs'.age: 28.gender: 'male'.address: 'Shunyi Mapo, Beijing' }
// Call the template engine
var htmlStr = template('tpl-user', data)
// Render the HTML structure
document.getElementById('user-box').innerHTML = htmlStr
</script>
</body>
Copy the code
5. XMLHttpRequest
XMLHttpRequest (XHR for short) is a Javascript object provided by the browser that allows you to request data resources on the server
Ajax functions in jQuery are wrapped around XHR objects
5.1 Initiate using XHRGET
request
Note: It is best to write open and send at the end to avoid unnecessary bugs, and open should be written before SEND!!
1. Create an XHR object
var xhr = new XMLHttpRequest()
// 4. Listen for onreadyStatechange
xhr.onreadystatechange = function () {
// readyState-- listen to xH object request status-- server response status
if (xhr.readyState === 4 && xhr.status === 200) {
// Get the data for the server response
console.log(xhr.responseText)
}
}
// 2. Call open
xhr.open('GET'.'http://www.liulongbin.top:3006/api/getbooks')
// 3. Call send
xhr.send()
Copy the code
1. readyState
Property – Represents the state of the current Ajax request
2. status
Attribute – Indicates the HTTP status code of the first line of the response packet
- 200 – The server is running properly
- 404 – The server does not have a URL to request
- 500 – The server reported an error
3. responseText
Property – Response stylistic data (extracted as text string)
- Note: It is usually converted to a JS object
let res = JSON.parse(xhr.responseText)
5.1.1 launchedWith parameters
The GET request
xhr.open('GET'.'http://www.liulongbin.top:3006/api/getbooks?id=1')
Copy the code
5.1.2 Query String
Query strings (URL parameters) are strings (variables) that are appended to the end of the URL to send information to the server.
url? Id = 1 & bookname = watched
5.1.3 The nature of the parameters carried by A GET request
Whether you use $.ajax(), $.get(), or simply use an XHR object to make a GET request, when you need to carry parameters, you essentially append them to the URL as a query string and send them to the server.
5.2 URL encoding and decoding
The URL address can contain only English letters, punctuation marks, and numbers
Therefore, Chinese characters must be encoded (escaped).
The browser automatically encodes the URL
Related knowledge reference
var str = 'Dark Horse Programmer';
/ / code encodeURI (STR)
var str2 = encodeURI(str);
console.log(str2); // %E9%BB%91%E9%A9%AC%E7%A8%8B%E5%BA%8F%E5%91%98
console.log('-- -- -- -- -- -- -- -- -- --');
/ / decoding decodeURI (STR)
var str3 = decodeURI('%E9%BB%91%E9%A9%AC');
console.log(str3); / / dark horse
Copy the code
5.3 Initiating an EVENT using XHRPOST
request
1. Create an XHR object
var xhr = new XMLHttpRequest()
// 2. Call open
xhr.open('POST'.'http://www.liulongbin.top:3006/api/addbook')
// 3. Set the content-type attribute.
// Tells the server that the data in the request format is in key-value pair format
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded')
// 4. Call send and specify the data to be sent
xhr.send('BookName = Water Margin &author= Shi Naian & Publisher = Shanghai Book Publishing House')
// 5
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
Copy the code
6. Data exchange format
Format of data transfer and exchange between server and client. (Example: XM and JSON)
XML 6.1
EXtensible Markup Language is a Markup Language similar to HTML
-
HTML is designed to describe the content on a web page and is the carrier of web content
-
XML is designed to transmit and store data and is the carrier of data
XML
Format bloated, and data irrelevant code, large volume, low transmission efficiency- in
Javascript
In the analyticalXML
More troublesome
6.2 JSON
JavaScript Object Notation
Nature: A string representing Javascript object data or array data, is a string.
Function: ** Stores and transfers data between a computer and a network.
JSON
Is a lightweight text data interchange format, similar in action toXML
For storing and transmitting data- than
XML
Smaller, faster, easier to parse.
6.2.1 Syntax Precautions
① Attribute names must be enclosed in double quotation marks
② String values must be wrapped in double quotation marks
The data type can be only six types: number, string, Boolean, NULL, array, and object.
④ You cannot write comments in the JSON file
⑤ The outermost layer of JSON must be an object or array format
⑥ Do not use undefined or functions as JSON values
6.2.2 JSON and JS
JSON is a string representation of a JS object, which uses text to represent information about a JS object, essentially a string.
/ / object
let obj={a:'hello' , b:'world'}
// Json string
let json=' {"a":"hello" , "b":"world"} '
Copy the code
- JSON string to JS object,
JSON.parse()
, deserialize - JS strings are converted to JSON objects,
JSON.stringfy()
The serialization
6.3 Encapsulating Ajax Functions
/ Test page.html /
<script src="./js/itheima.js"></script>
itheima({
method: ' '.url: ' '.data: {},
success:function(res){}})Copy the code
/itheima.js/
# 1.Processing the data argument, converting the object passed in to a JSON string/*** handles the data argument *@param {data} Data to be sent to the server *@returns {string} Return the concatenated query string name= Zs&age =10 */
function resolveData(data) {
var arr = []
for (var k in data) {
var str = k + '=' + data[k]
arr.push(str)
}
return arr.join('&');
}
# 2.Define the itheima functionfunction itheima(options) {
var xhr = new XMLHttpRequest();
// Convert the external parameter object to a query string
var qs = resolveData(options.data)
// Determine the request type and perform the send request accordingly
if (options.method.toUpperCase() === 'GET') {
// Initiate a GET request
xhr.open(options.method, options.url + '? ' + qs);
xhr.send();
} else if (options.method.toUpperCase() === 'POST') {
// Initiate a POST request
xhr.open(options.method, options.url);
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
xhr.send(qs);
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var result = JSON.parse(xhr.responseText)
options.success(result)
}
}
}
Copy the code
7. XMLHttpRequest new feature for Level2
- Disadvantages of older versions of XMLHttpRequest
-
Only text data can be transferred. It cannot be used to read or upload files
-
When transmitting and receiving data, there is no progress information, only a hint of completion
-
- New features
-
You can set the time limit for HTTP requests
-
You can use the FormData object to manage FormData
-
You can upload files
-
You can obtain the progress information of data transmission
-
7.1 Setting the HTTP Request Durationtimeout
<script>
var xhr = new XMLHttpRequest()
// Set the timeout. The maximum wait time is 30 milliseconds
xhr.timeout = 30
// Set the handler after the timeout
xhr.ontimeout = function () {
console.log('Request timed out! ')}// If the request times out, the following code will not be executed down
xhr.open('GET'.'http://www.liulongbin.top:3006/api/getbooks')
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
</script>
Copy the code
7.2 FormData objects manage FormData
HTML5 has added FormData objects
Form submission recommendations:
Use the Form’s Submit event, because there may be multiple submit buttons in the form, so that whichever button is clicked will trigger the form’s submit event
- The main reason to use FormData
Upload a file
. - Can only give
post
use - Get the form data directly
var fd = new FormData(form)
Must be added to the input formname
Properties; - If you add form data one by one,
var fd = new FormData(); fd.append('uname', 'zs')
, the name of the propertyuname
Is equivalent toname
7.2.1 Submit form data
1. Create a FormData object
var fd = new FormData()
// 2. Add the form item to FormData
fd.append('uname'.'zs')
fd.append('upwd'.'123456')
// 3. Create an XHR object
var xhr = new XMLHttpRequest()
// 4. Specify the request type and URL
xhr.open('POST'.'http://www.liulongbin.top:3006/api/formdata')
// 5. Submit the FormData object directly, exactly the same as submitting a web form
xhr.send(fd)
Copy the code
7.2.2 obtaining FormData new FormData(dom)
-
Jq: $(‘#form1’).serialize() allows you to directly retrieve the key-value pair format of a form with the name attribute
-
FormDate: New FormData(form) Automatically fills the form data into the FormData object created
// Get the form element
var form = document.querySelector('#form1')
// Listen for the submit event of the form element
form.addEventListener('submit'.function(e) {
e.preventDefault()
// Create a FormData object based on the form form. The FormData object is automatically populated with the form data
var fd = new FormData(form)
var xhr = new XMLHttpRequest()
xhr.open('POST'.'http://www.liulongbin.top:3006/api/formdata')
xhr.send(fd)
xhr.onreadystatechange = function() {}})Copy the code
7.3 Uploading files
<body>
<form id="form1">
<! -- 1. File selection box -->
<input type="file" id="file1" name="avatar" />
<! -- 2. Upload file button -->
<button id="btnUpload">Upload a file</button>
</form>
<br /><! --3.Img tag to display the image after uploading successfully --><img src="" alt="" id="img" width="800" />
<script>
let btn = document.querySelector('#btnUpload');
let file1 = document.querySelector('#file1');
let form1 = document.querySelector('#form1');
let img = document.querySelector('#img');
// 1. Add a submit event to the form
form1.addEventListener('submit'.function(e) {
// 2. Prevent the default submission of the form
e.preventDefault();
// 3. Check whether the image is uploaded *****
if (file1.files.length <= 0) return alert('Please upload pictures! ');
// 4. Use this to get the form data *****
let fd = new FormData(this); // FormData {}
let xhr = new XMLHttpRequest();
xhr.open('POST'.'http://www.liulongbin.top:3006/api/upload/avatar');
xhr.send(fd);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status == 200) {
let data = JSON.parse(xhr.responseText);
// data: {message: "Upload file successfully!" , status: 200, url: "/uploads/1625309578020_f15c0f22d3a143dcae417640c14b4410.jpg"}
if (data.status == 200) {
// Set the address of the image returned by the server to the SRC attribute of the tag
// Root path +data.url*****
img.src = 'http://www.liulongbin.top:3006' + data.url;
} else {
// Upload failedalert(data.message); }}}})</script>
</body>
Copy the code
7.4 Displaying the File upload Progress
7.4.1 Calculating the File upload Progress
In the new version of the XMLHttpRequest object, you can listen for the xhr.upload.onprogress event to get the file upload progress. The syntax is as follows:
// Create an XHR object
var xhr = new XMLHttpRequest()
// Listen for the onProgress event in xhr.upload
xhr.upload.onprogress = function(e) {
// e.lengthCompuTable is a Boolean value that indicates whether the currently uploaded resource has a computable length
if (e.lengthComputable) {
// E. loaded Transferred bytes
// e.total Total bytes to be transferred
var percentComplete = Math.ceil((e.loaded / e.total) * 100)}}Copy the code
7.4.2 Dynamically Setting a Progress Bar
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
// 1. Calculate the percentage of the current upload progress
var percentComplete = Math.ceil((e.loaded / e.total) * 100The $()'#percent')
// 2. Set the width of the progress bar
.attr('style'.'width:' + percentComplete + The '%')
// 3. Displays the current upload progress percentage
.html(percentComplete + The '%')}}Copy the code
7.4.3 Listening for the Upload Completion Event
xhr.upload.onload = function() {$('#percent')
// Remove the class style from the upload
.removeClass()
// Add the uploaded class style
.addClass('progress-bar progress-bar-success')}Copy the code
7.4.4 Complete code
<body>
<form id="form1">
<! -- 1. File selection box -->
<input type="file" id="file1" name="avatar" />
<! -- 2. Upload file button -->
<button id="btnUpload">Upload a file</button>
</form><! -- Bootstrap progress bar --><div class="progress" style="width: 500px; margin: 15px 10px;">
<div class="progress-bar progress-bar-striped active" style="width: 0%" id="percent">
0%
</div>
</div>
<br /><! --3.Img tag to display the image after uploading successfully --><img src="" alt="" id="img" width="800" />
<script>
$('#form1').on('submit'.function(e) {
e.preventDefault();
/ / determine whether to upload the file -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
/ / there are only a dom object files attribute $(' # file1). Get (0) and ($(' # file1) [0] is the same
if ($('#file1') [0].files.length <= 0) return alert('Please upload the file! ');
// create a formdata object and append formdata to it
let fd = new FormData(this);
// Create an asynchronous object -----------------
let xhr = new XMLHttpRequest();
// Monitor file upload progress -----------------------
xhr.upload.onprogress = uploadProgress;
// Monitor request status changes ---------------------------
// Pass in the XHR argument to the function via bind
xhr.onreadystatechange = stateChange.bind(null, xhr);
// It is best to write at the end to avoid bugs
xhr.open('POST'.'http://www.liulongbin.top:3006/api/upload/avatar')
xhr.send(fd);
})
function uploadProgress(e) {
if (e.lengthComputable) {
let percent = Math.ceil(e.loaded / e.total * 100) + The '%';
$('#percent').css('width', percent).html(percent);
// If the progress reaches 100%, change the progress bar style
if (percent == '100%') {
// The progress bar takes time to animate after the upload is complete
// So, after 0.5s, the style of the progress bar will change
setTimeout(() = >{$('#percent').removeClass().addClass('progress-bar progress-bar-success');
}, 500); }}}function stateChange(xhr) {
if (xhr.readyState == 4 && xhr.status == 200) {
let data = JSON.parse(xhr.responseText);
// Upload successfully, modify SRC attribute for img
if (data.status == 200) {$('#img').prop('src'.'http://www.liulongbin.top:3006' + data.url);
} else{ alert(data.message); }}}</script>
</body>
Copy the code
7.5 Sending a File Upload Request Using jquery
$.ajax({
method: 'POST'.url: 'http://www.liulongbin.top:3006/api/upload/avatar'.data: fd,
// Leave the content-type property unchanged and use the default content-type value for FormData
contentType: false.// Instead of urL-encoding the data in FormData, the FormData data is sent to the server as is
processData: false.success: function(res) {
console.log(res)
}
})
Copy the code
8. axios
Jquery provides DOM manipulation and Ajax manipulation; Axios only provides Ajax operations
Why use Axios?
Frameworks such as Vue don’t need programs to manipulate the DOM, so instead of using JQ, they use the AXIOS library that provides Ajax-only operations (AXIOS is lighter)
8.1 Axios initiates a GET request
axios.get('url', { params: { / * * / } }).then(callback)
Copy the code
8.2 Axios initiates a POST request
axios.post('url', { / * * / }).then(callback)
Copy the code
8.3 Directly Initiate a request using AXIos
axios({
method: 'Request Type'.url: 'Requested URL'.data: { /* POST data */ },
params: { /* GET argument */ }
}).then(callback)
1.Making a GET requestdocument.querySelector('#btn3').addEventListener('click'.function () {
var url = 'http://www.liulongbin.top:3006/api/get'
var paramsData = { name: 'Iron Man'.age: 35 }
axios({
method: 'GET'.url: url,
params: paramsData
}).then(function (res) {
console.log(res.data)
})
})
2.Making a POST requestdocument.querySelector('#btn4').addEventListener('click'.function () {
axios({
method: 'POST'.url: 'http://www.liulongbin.top:3006/api/post'.data: {
name: 'Wahaha'.age: 18.gender: 'woman'
}
}).then(function (res) {
console.log(res.data)
})
})
Copy the code
9. Same-origin policy
9.1 the same
If both pages have the same protocol, domain name (IP-find server) and port (80-find server program), then both pages have the same source.
The Same Origin policy (Same Origin Policy) is a security function provided by the browser. It does not allow resource interaction between non-same origin urls.
9.2 cross domain
What is cross-domain:
Same-origin indicates that the two urls have the same protocol, domain name, and port. Otherwise, the two urls are cross-domain
Cross-domain check:
The browser allows ajax cross-domain requests. However, the data returned from the cross-domain request will be checked by the browser to see if ajax cross-domain requests are allowed. If not, an error will be reported.
Browser interception of cross-domain requests
Implementing a cross-domain solution:
-
**JSONP: ** early, good compatibility (compatible with lower versions of IE). Is a temporary solution that front-end programmers are forced to come up with to solve cross-domain problems. The disadvantage is that only GET requests are supported, not POST requests.
-
**CORS: ** is a late arrival, a W3C standard that is the ultimate solution for cross-domain Ajax requests. Support for GET and POST requests. The disadvantage is that it is not compatible with some older browsers
-
Server proxy: the server side does not directly send cross-domain requests, but sets a proxy on the server side. The server side sends requests to the cross-domain proxy, and then returns the request results to the front end.
9.3 the json
The
JSONP is implemented by requesting the cross-domain data interface through the SRC attribute of the
- Purpose: To asynchronously retrieve data returned by the server interface
- Problem: The browser has checks for AJSX cross-domain requests
- Solution: Instead of using Ajax to send asynchronous requests, use script tags to make cross-domain requests, bypassing browser cross-domain checks for Ajax
/ Implement a simple jsonp/
// Define a 'SUCCESS' callback:<script>
function success(data) {
console.log('Get data:')
console.log(data)
}
</script>/ / by `<script></script>
Copy the code
Note: There is no relationship between JSONP and Ajax, and the way JSONP requests data cannot be called Ajax because JSONP does not use the XMLHttpRequest object
9.3.1 JQ sends JSONP data requests
By default, JSONP requests with jQuery automatically carry a callback=jQueryxxx parameter, which is the name of a randomly generated callback function
$.ajax({
url: 'http://ajax.frontend.itheima.net:3006/api/jsonp?name=zs&age=20'.// If you want to make a JSONP request using $.ajax(), you must specify datatype JSONP
dataType: 'jsonp'.// The name of the parameter to be sent to the server. The default value is callback
jsonp: 'callback'.// A custom callback function name. The default value is in the jQueryxxx format
jsonpCallback: 'abc'.success: function(res) {
console.log(res)
}
})
Copy the code
jQuery
In theJSONP
The implementation process of
JSONP in jQuery also implements cross-domain data access via SRC attributes of
-
Dynamically appends a
-
After the JSONP request succeeds, dynamically remove the
9.4 Caching Search Records
1.Define a global cache object// Cache objects
var cacheObj = {}
2.Save the search results to the cache object// Render the suggestion list
function getList(keyword) {
/ /... Omit other code
success(res){
// Add the keyword k and the suggestion list array value to the cache object
cacheObj[keyword] = res;
// Render the template structure againrenderList(res); }}3.Get search suggestions from the cache first// Listen for the keyup event of the text box
$('#ipt').on('keyup'.function() {
/ /... Omit other code
// Determine if there is any data in the cache before making a request
// If so, render the cached data directly to the page without sending ajax requests
if (cacheObj[keywords]) {
return renderSuggestList(cacheObj[keywords])
}
// Get the list of search suggestions
debounceSearch(keywords)
})
Copy the code
9.5 if you
-
The debounce policy is to delay the callback after an event is triggered for n seconds. If the event is triggered again within n seconds, the timer is reset. That is, something is scheduled to happen within a unit event, and if interrupted, the timer is reset
-
** Benefits: ** ensures that the callback will be executed only once, rather than frequently, when events are frequently triggered.
-
Application Scenarios:
- Get back to town. Reset the clock if you interrupt
- When a user enters a string of characters in the input box, the user can execute the query request only after the input is complete using the anti-shake policy. In this way, the number of requests (based on the start time of the last trigger) is effectively reduced and the request resources are saved.
var timer = null // 1. Anti-jitter timer
function debounceSearch(keywords) { // 2. Define the anti-shake function
timer = setTimeout(function() {
// Initiate a JSONP request
getSuggestList(keywords)
}, 500The $()}'#ipt').on('keyup'.function() { // 3. When the keyUP event is triggered, the timer is cleared immediately
clearTimeout(timer)
/ /... Omit other code
debounceSearch(keywords)
})
Copy the code
9.6 the throttle
- The throttle policy(
throttle
) Executes only once per unit of time, no matter how many times it triggers
9.6.1 Application Scenarios of Throttling
(1) The mouse continuously triggers an event (such as click), only triggers once per unit of time;
(2) Lazy loading to listen to the position of the scroll bar, but do not have to slide triggered every time, can reduce the frequency of calculation, and do not have to waste CPU resources;
9.6.2 Mouse Following Effect (Throttle Valve)
// Assume the browser takes 16ms to render the image
// So there is no need to reset the image position every time the mouse moves
// So you can set the position of the image again every 16ms
$(function() {
// 1
var angel = $('#angel');
// Step 1. Define the throttle valve
var timer = null;
// 2. Bind mousemove events
$(document).on('mousemove'.function(e) {
// Step 3: Check whether the throttle valve is empty. If not, the interval between the last execution is less than 16 milliseconds
if (timer) {
return
};
// 3. Set the position of the image
// Step 2: Enable the delay timer
timer = setTimeout(function() {
$(angel).css('top', e.pageY - 40 + 'px').css('left', e.pageX - 40 + 'px')
console.log('ok');
// When mouse following effect is set, empty timer throttle valve, convenient to start the timer next time
timer = null;
}, 16)})})Copy the code
10. HTTP
10.1 Communication Protocols
Communication Protocol refers to the rules and conventions that the two parties must abide by to complete the Communication.
The communication parties use the agreed format to send and receive messages, which is called communication protocol.
10.2 the HTTP protocol
HyperText Transfer Protocol (HyperText Transfer Protocol) specifies the Transfer format that must be followed when web content is transferred between the client and the server.
10.3 HTTP Request Messages
The request sent by the client is called AN HTTP request, and the message sent by the client to the server is called an HTTP request message or request packet.
The component of the HTTP request message
The HTTP request message consists of four parts: request line, header, blank line and request body.
10.3.1 request line
The request line consists of the request mode, URL, and HTTP protocol version, separated by Spaces.
10.3.2 Request Headers
The request header is used to describe the basic information of the client to inform the server about the client. For example, user-agent is used to specify the current type of browser.
Content-Type
Used to describe the format of data sent to the server; Accept is used to describe what type of return the client can receive.Accept-Language
Text content that describes which human language the client expects to receive.
Request headers by multiple linesKey/value pairsThe keys and values of each line are separated by colons
Request header – A common request header field MDN
10.3.3 blank line
The last request header field is followed by an empty line, notifying the server that the request header ends here.
A blank line in a request message that separates the request header from the request body
10.3.4 request body
The request body holds the data to be posted to the server.
Note: Only POST requests have request bodies, GET requests do not!
10.4 HTTP Response Messages
A response message is a message sent by the server to the client. It is also called a response message.
The HTTP response message consists of four parts: status line, response header, blank line and response body, as shown in the following figure:
10.4.1 status line
The status line consists of the HTTP protocol version, status code, and description of the status code, separated by Spaces
10.4.2 Response Headers
The response header is used to describe basic information about the server. The response header consists of multiple rows of key/value pairs, each row’s key and value separated by a colon.
- Response header – A common response header field
10.4.3 blank line
After the end of the last response header field, a blank line is followed to inform the client that the response header has ended.
A blank line in a response message that separates the response header from the response body.
10.4.4 response body
The response body stores the resource content that the server responds to the client.
10.5 HTTP Request Method
10.6 HTTP Response Status Code
HTTP Status Code, which identifies the Status of the response. MDN website
The HTTP status code consists of three decimal digits. The first decimal number defines the type of the status code, and the second two numbers are used to subdivide the status code.
10.6.1 2** Response status code related to success
Indicates that the server has successfully received and processed the request
10.6.2 3** Redirects related response status codes
Indicates that the server requires a client redirect and further action by the client to complete the resource request
10.6.3 Response status codes related to 4** client errors
Indicates that the client request contains illegal content, causing the request to fail.
10.6.4 5** Server error related response status code
An unexpected error occurs when the server fails to process a client request properly.