@toc Ajax features: local asynchronous refresh
Ajax profile
- Asynchronous JavaScript And XML refers to a web development technology that creates interactive, fast, dynamic web applications that can update parts of a web page without having to reload the entire page.
- AJAX = Asynchronous JavaScript and XML.
- AJAX is a technology that allows you to update parts of a web page without having to reload the entire page.
- Ajax is not a new programming language, but rather a technology for creating better, faster, and more interactive Web applications.
- Google Suggest uses AJAX to create a highly dynamic Web interface: When you type keywords into Google’s search box, JavaScript will send the characters 6. Send it to the server, which returns a list of search suggestions.
- Traditional web pages (that is, web pages that don’t use Ajax) require reloading the entire page in order to update content or submit a form.
- Using Ajax technology of web pages, through a small amount of data exchange in the background server, you can achieve asynchronous local updates.
- With Ajax, users can create direct, highly available, richer, and more dynamic Web user interfaces that mimic local desktop applications.
HTTP: request header Response header Request body Response body advantages:
- Communicate with the server without refreshing the page
- Allows partial page content to be updated based on user events
Disadvantages:
- No browsing history
- There are cross-domain problems (same origin)
- SEO is not friendly (not accessible to crawlers)
The HTTP protocol
HTTP protocol – stipulation
The request message
The focus is on format and parameters
GET/POST/url (md /? Host: Host: atguigu. Com Cookie: name=guigu content-type: Application/x-www-form-urlencoded/Application /json // Data content 2 types of user-agent: Chrome 83 has two types of data: If username=admin&password=admin or {username:"admin"," PWD ":"123"} If USERNAME :"admin"," PWD ":"123"} if USERNAME :"admin"," PWD ":"123"} if USERNAME :" ADMIN "," PWD ":"123"Copy the code
The response message
Line HTTP/1.1 Protocol version 200 Response status code OK Response status string {} Header Content-type: text/ HTML; Charset = UTF-8 Content-Length: 2048 Length Content-encoding: < HTML lang="en"> // Put the HTML content in the response packet <head> </head> <body> <div>1 <? php echo "Hello World!" ? > </div> </body> </html>Copy the code
The service generates cookie data to return to the browser, and then the request header cookie gets the data POST request body parameter format
- Content Type: application/x-www-form-urlencoded; charset=utf-8
For example: name=%E5%B0%8F%E6%98%8E&age= 12 2. Content-type: application/json; Charset = utF-8 Used for JSON string parameters. For example, {“name”: “%E5%B0%8F%E6%98%8E”, “age”: 12} 3. Content-type: multipart/form-data Used for text upload requests
- Response status string: 200 OK – Request succeeded. A – Generally used for GET and POST requests 201 Created – Created. A new resource is successfully requested and created. 401 Unauthorized – Unauthorized/request Requires user authentication. 404 Not Found – The Server cannot find resources based on client requests. Unable to complete request
- Different types of requests:
1.GET
: Reads data from the server 2.POST
: Adds new data to the server 3.PUT
: Updates data 4 on the server.DELETE
: Deletes data from the server
- The classification of the API
- REST API: restful
(1) Send a request for CRUD which operation is determined by the request mode (2) the same request path can be used for multiple operations (3) the request mode will use GET/POST/PUT/DELETE 2. The REST API: Restless (1) The request mode does not determine the CRUD operation of the request. (2) A request path corresponds to only one operation. (3) Generally only GET/POST Response header Request Request header Request row Request body Query String Parameters for the result of the URL resolution
-
Same-origin Policy: Protocol domain name Port numbers must be the same.
-
Cross-domain: The same origin policy is violated
Node
NPM management package tool Nodemon service restart plug-in:
- Automatically restart the service after the code is modified. You do not need to manually restart the service every time: Enter a value in the terminal
npm install -g nodemon
- Start: Enter: Nodemon file name in the terminal file path (
nodemon server.js
) - File cannot be loaded or an error is reported. You need to start terminal input as an administrator
Set-ExecutionPolicy RemoteSigned
- Then type the file to run again:
nodemon server.js
Download the Express framework — NPM I Express
The keyword
- xhr = new XMLHttpRequest(); Create an Ajax object
- Status Returns the status code 404 200 500
- ReadyState return status code: 0(uninitialized) 1(open call) 2(Send call) 3(server return partial result) 4(server return full result)
- Xhr.setrequestheader () sets the request header
- Response.setheader () sets the response header express
- response.setHeader(‘Access-Control-Allow-Origin’ , ‘*’); Set cross-domain Express to be allowed
- Xhr. timeout Sets the delay
- Xhr. onTimeout = function() {} Timeout callback
- Xhr. onError = () => {} The network is abnormal
- Xhr.onreadystatechange = function() {} event binding
- ReadyState return status code: 0(uninitialized) 1(open call) 2(Send call) 3(server return partial result) 4(server return full result)
10. StatusText returns a string 11.xhr.abort (); Cancel request 12. Status Returns status code 404 200 500
abort(); Cancel send request
jquery Ajax
jQuery.ajax(…) Some parameters: URL: Address of the request type: request mode (GET or POST) Headers: request header data: data to be sent contentType: Content encoding type of the message to be sent to the server (default: “application/x-www-form-urlencoded; Charset = utF-8 “) async: specifies whether async is async. Timeout: specifies whether async is async. BeforeSend: specifies whether async is async. Timeout: specifies whether async is async. Error: callback function executed after success (global) error: callback function executed after failure (global) : delivered to the server via request hair, telling the server the dataType accepted by the current client dataType: converts the data returned by the server into the specified type “XML “: “HTML “: Converts the content returned from the server side to plain text, which will be attempted if the JavaScript tag is included in the DOM insertion. “Script “: attempts to execute the returned value as JavaScript, and then convert the returned content from the server to plain text” JSON “: converts the returned content from the server to the corresponding JavaScript object “jsonp”: When a function is called using the JSONP form, such as “myURL? callback=?” JQuery will automatically replace? Is the correct function name to execute the callback function
Counterfeit class Ajax effect case
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
</head>
<body>
<div>
<p>Please enter the address to load:<span id="currentTime"></span></p>
<p>
<input type="text" id="url" value="https://baidu.com/">
<input type="button" value="Submit" onclick="loadpage()" id="submit">
</p>
</div>
<h3>Load page location:</h3>
<iframe src="" frameborder="0" style="width: 100%; height: 700px; border: 1px solid black;" id="iframePosition"></iframe>
<script type="text/javascript">
window.onload = function() {
let myDate = new Date(a);document.getElementById("currentTime").innerHTML = myDate.getTime();
};
function loadpage() {
let targetURL = document.getElementById('url').value;
console.log(targetURL);
document.getElementById('iframePosition').src = targetURL;
}
</script>
</body>
</html>
Copy the code
Ajax Sending Example
First experience of Building Node Ajax Express service
- Create a JS file to enable port HTTP: 8000 using the service set up by Node and Express
- Run the command in the path of the file terminal type: node plus the file name (basic use of Node Express.js)
- In the browser, enter the IP address of the local computer and the port 127.0.0.1:8000
- Go to the JS file service page you created and press CTRL + C to stop the node service
// 1
const { request, response } = require('express');
const express = require('express');
// 2. Create application objects
const app = express();
// 3. Create a routing rule
// Request encapsulates request packets
// Response encapsulates the response packet
app.get('/'.(request, response) = > {
// Set the response
response.send("Hello ExPress");
});
// 4. Listen to the port to start the service
app.listen(8000.() = > {
console.log('service started, listening on port 8000! ');
});
Copy the code
Node Ajax Express cross-domain Settings
// 1
const { request, response } = require('express');
const express = require('express');
// 2. Create application objects
const app = express();
// 3. Create a routing rule
// Request encapsulates request packets
// Response encapsulates the response packet
app.get('/server'.(request, response) = > {
/ / http://127.0.0.1:8000/server/server request lines of the second paragraph
// Set the response header to allow cross domains
response.setHeader('Accss-Control-Allow-Origin'.The '*');
// Set the response body
response.send("Hello Ajax");
});
// 4. Listen to the port to start the service
app.listen(8000.() = > {
console.log('service started, listening on port 8000! ');
});
Copy the code
GET Send request case
<! DOCTYPEhtml>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Ajax GET request</title>
<style>
#result {
width: 200px;
height: 200px;
border: 1px solid pink;
}
</style>
</head>
<body>
<button>I hit send request</button>
<div id="result"></div>
<script>
const btn = document.querySelector("button");
const result = document.getElementById("result");
// Event registration
btn.onclick = function() {
// console.log('Test');
// Create an object
const xhr = new XMLHttpRequest();
// Initialize, set the request method and URL
xhr.open('GET'.'http://127.0.0.1:8000/server? a=100&b=200&c=300');
/ / send
xhr.send();
// The event binding processes the result returned by the server
// on when.... when
/* RedayState is a property in an XHR (XMLHttpRequest) object with four states: 0(uninitialized), 1(open), 2(send), 3(server returns partial results), 4(server returns full results)*/
/ / change change
xhr.onreadystatechange = function() {
// Judge (server returns all results)
if(xhr.readyState === 4) {
// Check the response status. 400 404 200 500 2xx Succeeded
if(xhr.status >= 200 && xhr.status < 300) {
// The result line header is blank
// 1. Response line
console.log(xhr.status); / / status code
console.log(xhr.statusText); // Status string
console.log(xhr.getAllResponseHeaders()); // All response headers
console.log(xhr.response); / / response body
// Set the text of resultresult.innerHTML = xhr.response; }}}}</script>
</body>
</html>
Copy the code
POST send request case
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<style>
div {
width: 299px;
height: 200px;
border: 1px solid pink;
}
</style>
</head>
<body>
<div> </div>
<script>
const div = document.querySelector("div");
div.addEventListener("mouseover".() = > {
// Create an object
const xhr = new XMLHttpRequest();
// Initialize and set the URL
xhr.open('POST'.'HTTP: 127.0.0.1:8000 / server');
// Set the request header
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
xhr.setRequestHeader('name'.'gwetgfew-dsf');
/ / send
xhr.send('a=100&n=2321&d=21312'); // POST request body Settings
// xhr.send('a:100&n:2321&d:21312'); // Set the request body
// xhr.send('123213214'); // Set the request body
// Event binding
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status >= 200 && xhr.status < 300) { div.innerHTML = xhr.response; }}}});</script>
</body>
</html>
Copy the code
JSON Data transmission
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<style>
div {
width: 520px;
height: 200px;
border: 1px solid pink;
}
</style>
</head>
<body>
<div></div>
<script>
const div = document.querySelector("div");
// Event binding
window.onkeydown = function() {
// Send the request
const xhr = new XMLHttpRequest();
// Set the data type of the response body
xhr.responseType = 'json'; // Automatic conversion to objects does not require manual conversion
/ / initialization
xhr.open('GET'.'HTTP: 127.0.0.1:8000 / json - server');
/ / send
xhr.send();
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status >= 200 && xhr.status < 300 ) {
// console.log(xhr.response);
// div.innerHTML = xhr.response;
// Convert data manually
// let data = JSON.parse(xhr.response);
// console.log(data instanceof Object);
// div.innerHTML = data.name;
// Automatically convert data
console.log(xhr.response instanceof Object); div.innerHTML = xhr.response.name; }}}}</script>
</body>
</html>
Copy the code
IE Cache problem
If you open Internet Explorer, the Ajax data will be cached in the browser, and the next time you make an Ajax request, you will first access the local cache. This will not allow you to receive new data properly, so you can fix this by adding a timestamp to the URL so that every time you get the latest data
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<style>
div {
width: 200px;
height: 200px;
border: 1px solid pink;
}
</style>
</head>
<body>
<button>Click on the</button>
<div>1</div>
<script>
const div = document.getElementsByTagName("div") [0];
const btn = document.getElementsByTagName("button") [0];
btn.addEventListener("click".function() {
const xhr = new XMLHttpRequest();
xhr.open("GET"."Http://127.0.0.1:8000/ie? t="+Date.now());
xhr.send();
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status >= 200 && xhr.status < 300) { div.innerHTML = xhr.response; }}}; });</script>
</body>
</html>
Copy the code
Ajax cancel request
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
</head>
<body>
<button>Click on send</button>
<button>Click cancel</button>
<script>
const btn = document.getElementsByTagName("button");
let x = null;
btn[0].onclick = function() {
x = new XMLHttpRequest();
x.open("GET"."http://127.0.0.1:8000/delete");
x.send();
x.onreadystatechange = function() {}; }// abort
btn[1].onclick = () = > {
x.abort();
}
</script>
</body>
</html>
Copy the code
Repeat request solution to throttle valve
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
</head>
<body>
<button>Click on send</button>
<script>
const btn = document.getElementsByTagName("button");
let x = null;
// represents the variable
let flag = false; // Whether the AJAX request is being sent
btn[0].onclick = function() {
if(flag) {x.abort(); } x =new XMLHttpRequest();
flag = true;
x.open("GET"."http://127.0.0.1:8000/delete");
x.send();
x.onreadystatechange = function() {
if(x.readyState === 4) {
// Modify the identifier variable
flag = false; }}; }// abort
btn[1].onclick = () = > {
x.abort();
}
</script>
</body>
</html>
Copy the code
jquery -Ajax
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Jquery sends the Ajax request</title>
<link rel="stylesheet" href="The bootstrap - 3.3.2 rainfall distribution on 10-12 - dist/CSS/bootstrap. Min. CSS">
<script src="The bootstrap - 3.3.2 rainfall distribution on 10-12 - dist/js/jquery - 3.5.1 track of. Min. Js." "></script>
<script src="The bootstrap - 3.3.2 rainfall distribution on 10-12 - dist/js/bootstrap. Min. Js." "></script>
</head>
<body>
<div class="container">
<h2 >JQuery sends the Ajax request</h2>
<button type="button" class="btn btn-danger">GET</button>
<button type="button" class="btn btn-primary">POST</button>
<button type="button" class="btn btn-success">Generic method Ajax</button>
</div>
<script>
$('button').eq(0).click(function() {
$.get('http://127.0.0.1:8000/jquery-server', {a:100.n:123}, function(data) {
console.log(data);
},'json');
});
$('button').eq(1).click(function() {
$.post('http://127.0.0.1:8000/jquery-server', {a:123.n:100}, function(data) {
console.log(data);
});
});
$('button').eq(2).click(function() {
$.ajax({
// url
url: 'http://127.0.0.1:8000/jquery-server'./ / parameters
data: {a:100.b:200},
/ / type
type: 'GET'.// Response body result
dataType: 'json'.// Successful callback
success: function(data) {
console.log(data);
},
// Timeout period
timeout: 2000.// Failed callback
error: function() {
console.log('Wrong! ');
},
/ / headers
headers: {
a: 120.b:230}}); });</script>
</body>
</html>
Copy the code
Axios-ajax sends the request
Github.com/axios/axios official
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>axios</title>
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
<button>GET</button>
<button>POST</button>
<button>Ajax</button>
<script>
const btns = document.querySelectorAll('button');
axios.defaults.baseURL = 'http://127.0.0.1:8000';
btns[0].onclick = function() {
/ / configuration baseURL
axios.get('/axios-server', {/ / url parameters
params: {
id: 120.vip: 711
},
// Request header
headers: {
name: 'atguigu'.age: 18,
}
}).then(value= > {
console.log(value);
});
}
btns[1].onclick = function() {
axios.post('/axios-server', {
username: 'admin'.password: 'admin'}, {/ / url parameters
params: {
id: 147.vip: 258
},
/ / request header
headers: {height: 180.weight: 180}}); } btns[2].onclick = function() {
axios({
// Request method
method: 'POST'.// url
url: '/axios-server'./ / url parameters
params: {
id: 1012.leave: 9120
},
/ / headers
headers: {
a: 100.b: 200
},
// Request body parameters
data: {
username: 'admin'.password: 'admin'
}
}).then(response= > {
console.log(response);
// Response status code
console.log(response.status);
// Response status string
console.log(response.statusText);
// The response header
console.log(response.headers);
// Response body information
console.log(response.data);
});
};
</script>
</body>
</html>
Copy the code
The fetch send Ajax
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
</head>
<body>
<button>Sending Ajax requests</button>
<script>
const btn = document.querySelector("button");
btn.onclick = () = > {
fetch('http://127.0.0.1:8000/fetch-server? vip=10', {// Request method
method: 'POST'./ / request header
headers: {
name: 'admin'.passwd: 'admin'
},
/ / request body
body: 'a:100&b:1000'
}).then(response= > {
// console.log(value);
// return response.text();
return response.json();
}).then(response= > {
console.log(response);
});
};
</script>
</body>
</html>
Copy the code
All of the above case JS files
// 1
const { request, response } = require('express');
const express = require('express');
// 2. Create application objects
const app = express();
// 3. Create a routing rule
// Request encapsulates request packets
// Response encapsulates the response packet
app.get('/'.(request, response) = > {
response.send("Hello ExPress");
});
// Get the JS code
app.get('/server'.(request, response) = > {
/ / http://127.0.0.1:8000/server/server triggers the second paragraph
// Set the response header to allow cross domains
response.setHeader('Access-Control-Allow-Origin' , The '*');
// Set the response header
response.send("Hello ExPress GET ");
});
// Post JS code
app.all('/server'.(request, response) = > {
/ / http://127.0.0.1:8000/server/server triggers the second paragraph
// Set the response header to allow cross domains
response.setHeader('Access-Control-Allow-Origin' , The '*');
// Response header Receives custom request headers
response.setHeader('Access-Control-Allow-Headers'.The '*');
// Set the response header
response.send("Hello ExPress POST ");
});
// The all JSON JS code sets all to accept all HTTP requests because it sets the custom request header name
app.all('/json-server'.(request, response) = > {
// Set the response header to allow cross domains
response.setHeader('Access-Control-Allow-Origin' , The '*');
// Response header Receives custom request headers
response.setHeader('Access-Control-Allow-Headers'.The '*');
// Respond to a data
const data = {
name: 'atguigu'};// JSON.stringify(data)
// Decompose the contents of the object into strings using json.stringify (element)
let str = JSON.stringify(data);
// Set the response header
response.send(str);
});
// Ie cache problem JS code
app.get('/ie'.(request, response) = > {
// Set the response header to allow cross domains
response.setHeader("Access-Control-Allow-Origin"."*");
response.send("Hello IE - 2 ");
});
// Delay the response JS code
app.all('/delete'.(request, response) = > {
response.setHeader("Access-Control-Allow-Origin"."*");
response.setHeader("Access-Control-Allow-Headers"."*");
setTimeout(function() {
response.send("Hello delay response");
},1000);
});
/ / jQuery service
app.all('/jquery-server'.(request, response) = > {
// Set the response header to allow cross domains
response.setHeader("Access-Control-Allow-Origin"."*");
response.setHeader("Access-Control-Allow-Headers"."*");
// response.send("Hello jQuery Ajax");
const data = {name : 'Still Silicon Valley'};
// let str = JSON.stringify(data);
response.send(JSON.stringify(data));
});
/ / axios service
app.all('/axios-server'.(request, response) = > {
// Set the response header to allow cross domains
response.setHeader("Access-Control-Allow-Origin"."*");
response.setHeader("Access-Control-Allow-Headers"."*");
// response.send("Hello jQuery Ajax");
const data = {name : 'Still Silicon Valley'};
// let str = JSON.stringify(data);
response.send(JSON.stringify(data));
});
/ / the fetch service
app.all('/fetch-server'.(request, response) = > {
// Set the response header to allow cross domains
response.setHeader("Access-Control-Allow-Origin"."*");
response.setHeader("Access-Control-Allow-Headers"."*");
// response.send("Hello jQuery Ajax");
const data = {name : 'Still Silicon Valley'};
// let str = JSON.stringify(data);
response.send(JSON.stringify(data));
});
// 4. Listen to the port to start the service
app.listen(8000.() = > {
console.log('service started, listening on port 8000! ');
});
Copy the code
Homologous Sending Case
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Home page</title>
</head>
<body>
<h1>Yet in silicon valley</h1>
<button>Click Send user data</button>
<script>
const btn = document.querySelector("button");
btn.onclick = function() {
// Create an object
const x = new XMLHttpRequest();
/ * initialized Because it meet the same-origin policy is in operation, so the url http://127.0.0.1:7000/data in front of the same address can be abbreviated Just add the back of the link to that can * /
x.open("GET"."/data");
/ / send
x.send();
x.onreadystatechange = function() {
if(x.readyState === 4) {
if(x.status >= 200 && x.status < 300 ) {
console.log(x.response); }}}};</script>
</body>
</html>
Copy the code
Js file
const { request, response } = require('express');
const express = require('express');
const app = express();
app.get('/home'.(request, response) = > {
// Respond to a page
response.sendFile(__dirname + '/index.html');
});
/ / the same
app.get('/data'.(request, response) = > {
response.send('User Data');
});
app.listen(7000.() = > {
console.log('Port 7000 service started! ~ ');
});
Copy the code
JSONP sending case
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<style>
#result {
width: 299px;
height: 200px;
border: 1px solid pink;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
function fn1(data) {
const result = document.getElementById("result");
result.innerHTML = data.name;
};
</script>
<! Cross domain request using script tag cross domain -->
<! -- < script SRC = "http://127.0.0.1:5500/%E8%B7%A8%E5%9F%9F/JSONP/js/app.js" > < / script > -- >
<script src="http://127.0.0.1:8000/jsonp-server"></script>
</body>
</html>
Copy the code
Js file
const { request, response } = require('express');
const express = require('express');
const app = express();
/ / the json service
app.all('/jsonp-server'.(request, response) = > {
// response.send('Hello Jsonp-server');
// response.send('console.log("Hello Jsonp-server")');
const data = {
name : 'Silicon Valley Athuiug'
};
// Convert the data to a string
let str = JSON.stringify(data);
// Return the result end with no special response header. Use the template string to parse the variable without using the citation
response.end(`fn(${str}) `);
});
// 4. Listen to the port to start the service
app.listen(8000.() = > {
console.log('service started, listening on port 8000! ');
});
Copy the code
Json practice
Send directly without judgment
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="username"> <p></p>
<script>
const input = document.querySelector("#username");
const p = document.querySelector("p");
// Declare fn
function fn(data) {
input.style.border = "1px solid #f00";
// Modify the text information of the p label
p.innerHTML = data.msg;
};
input.onblur = function() {
// Get the value the user entered
let username = this.value;
// Send a request to the server to check if the user name has a create script tag
const script = document.createElement("script");
// Set the SRC attribute of the tag
script.src = 'http://127.0.0.1:8000/check-username';
// 3. Add script tags to the document
document.body.appendChild(script);
};
// The script tag sends a request to the server and returns an fn() function call to the browser parser that can be executed to parse the code sent
</script>
</body>
</html>
Copy the code
Js file
// 1
const { request, response } = require('express');
const express = require('express');
// 2. Create application objects
const app = express();
// 3. Create a routing rule
// Request encapsulates request packets
// Response encapsulates the response packet
// User name detects whether a service exists
app.all('/check-username'.(request, response) = > {
// response.send('console.log("Hello Jsonp-server")');
const data = {
exist: 1.msg: 'User already exists'
};
// Convert the data to a string
let str = JSON.stringify(data);
// Return the result end with no special response header. Use the template string to parse the variable without using the citation
response.end(`fn(${str}) `);
});
// 4. Listen to the port to start the service
app.listen(8000.() = > {
console.log('service started, listening on port 8000! ');
});
Copy the code
jQuery-jsonp
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<style>
div {
width: 200px;
height: 200px;
border: 1px solid pink;
}
</style>
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<button>Click send JSON request</button>
<div>
</div>
<script>
$('button').eq(0).click(function() {
$.getJSON('http://127.0.0.1:8000/jquery-jsonp-server? callback=? '.function(data) {
// console.log(data);
$('div').html(` name:${data.name}< br > campus:${data.city}
`);
});
});
</script>
</body>
</html>
Copy the code
Js file
// 1
const { request, response } = require('express');
const express = require('express');
// 2. Create application objects
const app = express();
// 3. Create a routing rule
// Request encapsulates request packets
// Response encapsulates the response packet
app.all('/jquery-jsonp-server'.(request, response) = > {
// response.send('console.log("Hello Jsonp-server")');
const data = {
name: 'Still Silicon Valley'.city: ['Shanghai'.'Beijing'.'shenzhen']};// Convert the data to a string
let str = JSON.stringify(data);
// Receive the callback argument concatenated into a string for function execution
let cb = request.query.callback;
// Return the result end with no special response header. Use the template string to parse the variable without using the citation
response.end(`${cb}(${str}) `);
});
// 4. Listen to the port to start the service
app.listen(8000.() = > {
console.log('service started, listening on port 8000! ');
});
Copy the code
cors
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<style>
#result {
width: 1000px;
height: 100px;
border: 1px solid pink;
}
</style>
</head>
<body>
<button>Click send JSON request</button>
<div id="result"></div>
<script>
const btn = document.querySelector('button');
// Create an object
const x = new XMLHttpRequest();
x.open("GEt".'http://127.0.0.1:8000/cors-server');
x.send();
x.onreadystatechange = () = > {
if(x.readyState === 4) {
if(x.status >= 200 && x.status < 300) {
console.log(x.response); }}}</script>
</body>
</html>
Copy the code
// 1
const { request, response } = require('express');
const express = require('express');
// 2. Create application objects
const app = express();
// 3. Create a routing rule
// Request encapsulates request packets
// Response encapsulates the response packet
app.all('/cors-server'.(request,response) = > {
// Set the response header
response.setHeader('Access-Control-Allow-Origin' , "*");
response.setHeader('Access-Control-Allow-Headers' , "*");
response.setHeader('Access-Control-Allow-Mothod' , "*");
/ / response. SetHeader (' Access - Control - Allow - Origin, "http://127.0.0.1:5500"); Only 5500 access is allowed
response.send("Hello Cors");
});
// 4. Listen to the port to start the service
app.listen(8000.() = > {
console.log('service started, listening on port 8000! ');
});
Copy the code