get request
get.html
Four steps
<!DOCTYPE html> <body> <button onclick="getReq()">get request</button> <script> function getReq(){ //1. Create an XMLHttpRequest object let xhr = new XMLHttpRequest(); //2. Call the open() method to open the connection //Parameters: method: string, url: string xhr.open("get","./data.php"); //3. Send Request xhr.send(); //4. Changes in monitoring status xhr.onreadystatechange = function(){ //Judgement status value 0-4, five states, 4 means final completion if(xhr.readyState === 4){ //Judgement Status Code if(xhr.status === 200){ console.log(xhr.responseText); } } } } </script> </body> </html>
data.php
<?php echo "hello ajax" ?>
get request with parameters
get.html
get method passes parameter stitching behind url
<!DOCTYPE html> <body> <button onclick="getReq()">get request</button> <script> function getReq(){ //Create an XMLHttpRequest object let xhr = new XMLHttpRequest(); //Call the open() method to open the connection //Parameters: method: string, url: string xhr.open("get","./data.php?id=101"); //Send Request xhr.send(); //Change in listening state xhr.onreadystatechange = function(){ //Judgement status value 0-4, five states, 4 means final completion if(xhr.readyState === 4){ //Judgement Status Code if(xhr.status === 200){ console.log(xhr.responseText); } } } } </script> </body> </html>
data.php
<?php $id = $_GET["id"]; echo "hello ajax $id" ?>
output
json string and json format
get.html
json string and json format
<!DOCTYPE html> <body> <button onclick="getReq()">get request</button> <script> function getReq(){ //Create an XMLHttpRequest object let xhr = new XMLHttpRequest(); //Call the open() method to open the connection //Parameters: method: string, url: string xhr.open("get","./data.php?id=101"); //Send Request xhr.send(); //Change in listening state xhr.onreadystatechange = function(){ //Judgement status value 0-4, five states, 4 means final completion if(xhr.readyState === 4){ //Judgement Status Code if(xhr.status === 200){ console.log(xhr.responseText); console.log(JSON.parse(xhr.responseText)); } } } } </script> </body> </html>
data.php
<?php $id = $_GET["id"]; echo json_encode(array( 'id' => $id, 'title' => 'hello ajax' )) ?>
Encapsulation of get requests
getAjax.html
How to remove a character at the end &? Use slice function
<!DOCTYPE html> <body> <button onclick="get()">post request</button> <script> function get(){ let per = { name:"zhuobing", age: 19 } getAjax("./data.php",per,function(resp){ console.log(resp); },true) } //Encapsulation function: getAjax() //url:Requested address //query: Requested parameter, is an object //Callback:callback function //isJson: Resolve to JSON or not function getAjax(url,query,callback,isJson){ if(query){ url += '?'; for(let key in query){ url += `${key}=${query[key]}&` } url = url.slice(0,-1); } let xhr = new XMLHttpRequest(); xhr.open("get",url); xhr.send(); xhr.onreadystatechange = function(){ //Judgement status value 0-4, five states, 4 means final completion if(xhr.readyState === 4){ //Judgement Status Code if(xhr.status === 200){ let resp = isJson? JSON.parse(xhr.responseText):xhr.responseText; callback(resp); } } } } </script> </body> </html>
data.php
<?php $name = $_GET["name"]; $age = $_GET["age"]; echo json_encode(array( "name" => $name, "age" => $age )) ?>
Encapsulation of a promise-based get request
test.html
<!DOCTYPE html> <html lang="zh"> <body> <button onclick="sendMsg()">get request by promise</button> <script src="./utils.js"></script> <script> function sendMsg() { utils.fetch("./data2.php", { name: "zhuobing", age: 19 }, true).then(function (resp) { console.log(resp); }) } </script> </body> </html>
utils.js
The key to promise is to return a new promise() object
const utils = { //promise-based get encapsulation fetch:function(url,query,isJson){ if(query){ url += '?'; for(let key in query){ url += `${key}=${query[key]}&` } url = url.slice(0,-1); } return new Promise((resolve,reject)=>{ let xhr = new XMLHttpRequest(); xhr.open("get",url); xhr.send(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ //Judgement Status Code if(xhr.status === 200){ let resp = isJson? JSON.parse(xhr.responseText):xhr.responseText; resolve(resp); }else{ reject(); } } } }) } }
post request
post.html
Writing Template Strings in JavaScript
<!DOCTYPE html> <body> <button onclick="getReq()">post request</button> <div></div> <script> function getReq(){ //Create an XMLHttpRequest object let xhr = new XMLHttpRequest(); //Call the open() method to open the connection //Parameters: method: string, url: string xhr.open("post","./data.php"); //Set Content-Type of Request Header xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //Send Request xhr.send("name=zhuobing&age=19"); //Change in listening state xhr.onreadystatechange = function(){ //Judgement status value 0-4, five states, 4 means final completion if(xhr.readyState === 4){ //Judgement Status Code if(xhr.status === 200){ let resp = JSON.parse(xhr.responseText); document.querySelector("div").innerHTML=` <h2>name=${resp.name}</h2> <h2>age=${resp.age}</h2> ` } } } } </script> </body> </html>
data.php
<?php $name = $_POST["name"]; $age = $_POST["age"]; echo json_encode(array( "name" => $name, "age" => $age )) ?>
output
Differences between post and get pass parameters
Encapsulation of post request
post.html
<!DOCTYPE html> <body> <button onclick="post()">post request</button> <div></div> <script> function post(){ let per = { name:"zhuobing", age: 19 } postAjax("./data.php",per,function(resp){ console.log(resp); },true) } function postAjax(url,query,callback,isJson){ let para = ''; if(query){ for(let key in query){ para += `${key}=${query[key]}&` } para = para.slice(0,-1); } console.log(para); let xhr = new XMLHttpRequest(); xhr.open("post",url); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(para); xhr.onreadystatechange = function(){ //Judgement status value 0-4, five states, 4 means final completion if(xhr.readyState === 4){ //Judgement Status Code if(xhr.status === 200){ let resp = isJson? JSON.parse(xhr.responseText):xhr.responseText; callback(resp); } } } } </script> </body> </html>
data.php
<?php $name = $_POST["name"]; $age = $_POST["age"]; echo json_encode(array( "name" => $name, "age" => $age )) ?>
utils.js encapsulates get and post requests
The get and post methods are encapsulated into two
test.html
How to invoke the external tool utils.js
<!DOCTYPE html> <body> <button onclick="post()">post request</button> <button onclick="get()">get request</button> <script src="./utils.js"></script> <script> function post(){ let per = { name:"postMethod", age: 19 } //post Request Data utils.post("./data.php",per,function(resp){ console.log(resp); },true) } function get(){ let per = { name:"getMethod", age: 19 } //Request data by get utils.get("./data2.php",per,function(resp){ console.log(resp); },true) } </script> </body> </html>
utils.js
Code Folding
const utils = { get: function(url,query,callback,isJson){ if(query){ url += '?'; for(let key in query){ url += `${key}=${query[key]}&` } url = url.slice(0,-1); } let xhr = new XMLHttpRequest(); xhr.open("get",url); xhr.send(); xhr.onreadystatechange = function(){ //Judgement status value 0-4, five states, 4 means final completion if(xhr.readyState === 4){ //Judgement Status Code if(xhr.status === 200){ let resp = isJson? JSON.parse(xhr.responseText):xhr.responseText; callback(resp); } } } }, post: function(url,query,callback,isJson){ let para = ''; if(query){ for(let key in query){ para += `${key}=${query[key]}&` } para = para.slice(0,-1); } let xhr = new XMLHttpRequest(); xhr.open("post",url); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(para); xhr.onreadystatechange = function(){ //Judgement status value 0-4, five states, 4 means final completion if(xhr.readyState === 4){ //Judgement Status Code if(xhr.status === 200){ let resp = isJson? JSON.parse(xhr.responseText):xhr.responseText; callback(resp); } } } } }
The get and post methods are encapsulated into one
test.html
<!DOCTYPE html> <body> <button onclick="request()">request</button> <script src="./utils.js"></script> <script> function request(){ utils.ajax({ method:'get', url:'data2.php', query:{name:'getMethod',age:19}, callback:function(resp){ console.log(resp); }, isJson:true }); utils.ajax({ method:'post', url:'data.php', query:{name:'postMethod',age:19}, callback:function(resp){ console.log(resp); }, isJson:true }); } </script> </body> </html>
utils.js
Code Folding
const utils = { // params: object {method,url,query,callback,isJson} ajax: function(params){ let xhr = new XMLHttpRequest(); if(params.method.toLowerCase() ==="post"){ let para = ''; if(params.query){ for(let key in params.query){ para += `${key}=${params.query[key]}&` } para = para.slice(0,-1); } xhr.open("post",params.url); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(para); }else{ if(params.query){ params.url += '?'; for(let key in params.query){ params.url += `${key}=${params.query[key]}&` } params.url = params.url.slice(0,-1); } xhr.open("get",params.url); xhr.send(); } xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if(xhr.status === 200){ let resp = params.isJson? JSON.parse(xhr.responseText):xhr.responseText; params.callback(resp); } } } } }
ajax example-paragraph request
index.html
sid transfer process
<!DOCTYPE html> <html lang="zh"> <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>ajax</title> </head> <body> <ul id="wrap"></ul> <script src="./utils.js"></script> <script> utils.ajax({ method:"get", url:"https://api.apiopen.top/getJoke", query: null, callback: function(resp){ let html = ''; resp.result.forEach(ele => { html += ` <li> <h3>${ele.text}</h3> <button data-id=${ele.sid}>View Authors</button> </li> ` }); document.querySelector("#wrap").innerHTML = html; }, isJson:true }); document.querySelector("#wrap").onclick = function(e){ let target = e.target; if(target.tagName === "BUTTON"){ let id = target.getAttribute("data-id"); utils.ajax({ method: "get", url: "https://api.apiopen.top/getSingleJoke", query: {sid:id}, callback:function(resp){ let name = resp.result.name; let span = document.createElement("span"); span.innerHTML = name; target.parentNode.appendChild(span); }, isJson:true }); } } </script> </body> </html>
utils.js
const utils = { // params: object {method,url,query,callback,isJson} ajax: function(params){ let xhr = new XMLHttpRequest(); if(params.method.toLowerCase() ==="post"){ let para = ''; if(params.query){ for(let key in params.query){ para += `${key}=${params.query[key]}&` } para = para.slice(0,-1); } xhr.open("post",params.url); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(para); }else{ if(params.query){ params.url += '?'; for(let key in params.query){ params.url += `${key}=${params.query[key]}&` } params.url = params.url.slice(0,-1); } xhr.open("get",params.url); xhr.send(); } xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if(xhr.status === 200){ let resp = params.isJson? JSON.parse(xhr.responseText):xhr.responseText; params.callback(resp); } } } } }
OUTPUT
fetch method
fetch-based get request
test.html
Why need more than one then()
<!DOCTYPE html> <html lang="zh"> <body> <button onclick="sendMsg()">get request by promise</button> <script> function sendMsg() { fetch("./data2.php?name=zhuobing&age=19") .then(function(resp){ return resp.json() }) .then(function (resp) { console.log(resp); }) } </script> </body> </html>
fetch-based post request
test.html
This is problematic code, and the compiler did not error, but it just couldn't find the cause
<!DOCTYPE html> <html lang="zh"> <body> <button onclick="sendMsg()">post request by promise</button> <script> function sendMsg() { fetch("https://api.apiopen.top/getSingleJoke", { method: 'post', body: JSON.stringify({ 'sid': 28822773 })//Here is the parameter to pass }) .then(response => response.json()) .then(data => { console.log(data) }) } </script> </body> </html>
test.html
This code is the modified code and works as expected
Modifications
Where the problem occurs
<!DOCTYPE html> <html lang="zh"> <body> <button onclick="sendMsg()">post request by promise</button> <script> function sendMsg() { fetch("https://api.apiopen.top/getSingleJoke", { method: 'post', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, // Body: JSON.stringify ({sid: 28822773})// No error, but that's why the error was not found body: "sid=28822773"//Did you get the right result? }) .then(response => response.json()) .then(data => { console.log(data) }) } </script> </body> </html>
Reason Analysis
fetch Posts transfer data in the form of JSON.stringify():
fetch('http://www.tingchunyu.com/test/fetch_test/fetch_getuser_test.php', { body: JSON.stringify({id:666}), headers: { 'content-type': 'application/json' }, method: 'POST', }) .then(response => { if (response.ok){//Determine whether the request was successful return response.json() } throw new Error('An error occurred in the request') }) .then(data=>{ console.log(data) }) .catch(error => { console.log(error) })
But writing the background like above always receives null s in the same way that variables were previously received. This is because the data submitted to the server in this way is a json data, not traditional formdata. As shown in the following figure:
So there are two ways to get data in the background
- Make the following changes to the format of the code body above
body: 'id=666' //If there are multiple parameters that can be connected with'&', for ex amp le, body:'id=666&type=0'
But this is a bit cumbersome if there are many parameters to pass.
The second way is to leave the above code unchanged. Modify the way background receive parameters are received. Take PHP for example:
// Will $_ POST['id'] is modified to $data = json_decode(file_get_contents('php://input'),true); $id = $data['id'];//This will allow you to receive the ID
Browser Homology Policy
Definition
If the protocol, domain name and port number in the two page addresses are identical, they are of the same origin.
Limitations of the homology policy: You cannot request data from different domains through ajax, or script DOM s from different domains.
Why use homology policy
Homology restrictions are mostly set for security. If there are no homology restrictions for other data such as cookie s in the browser to be read arbitrarily, DOM to operate arbitrarily in different domains, ajax to request arbitrarily will leak these private data if you browse malicious websites
Give an example
Principle of src attribute openness
Example 1
test.html
<!DOCTYPE html> <html lang="en"> <body> <script> function fun(resp){ console.log(resp); } </script> <script src="http://localhost/data3.php"></script> </body> </html>
data3.php
Return Results
Because no matter what type of problem the script tag src introduces, it will be executed as js code, so fun(123) is executed as a function, that is, the function written above, with only one parameter added to the php code at the back
<?php echo "fun(123)"; ?>
output
Example 1 (dynamic function name)
test.html
Cross-domain process
<!DOCTYPE html> <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> <script> function adfsadsfadsf(resp){ console.log(resp); } </script> <script src="http://localhost/data3.php?funname=adfsadsfadsf"></script> </body> </html>
data3.php
The process of passing function names
<?php $fun = $_GET["funname"]; echo "$fun(123)"; ?>
Results returned by backend
Example (Baidu Dynamic Search Box)
test.html
Why do I need to [External chain picture transfer failed, source station may have anti-theft chain mechanism, we recommend to save the picture and upload it directly (img-iy13l6oX-163402268) (C:\UserszhuossAppDataRoamingTyporatypora-user-imagesimage-202158;58.png)]
Because if you don't remove, there will be many script tags in html, which will seriously affect browser performance
callback
<!DOCTYPE html> <html lang="zh"> <head> </head> <body> <input id="search" type="text"> <ul id="list"></ul> <script> let search = document.querySelector("#search") search.onkeyup = function(){ let text = search.value let script = document.createElement("script") script.src = `https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=${text}&cb=fun` document.body.appendChild(script) document.body.removeChild(script) } function fun(resp){ let html = '' resp.s.forEach(ele => { html += `<li>${ele}</li>` }); document.querySelector("#list").innerHTML = html } </script> </body> </html>
output
Three and four handshakes
Preliminary understanding
It takes three handshakes to establish a connection and four waves to disconnect