Ajax
Ajax is a technical solution, but it is not a new technology. It relies on existing css/html/javascript, and the core of the dependency is the XMLHttpRequest object provided by the browser, which allows the browser to make HTTP requests and receive HTTP responses. The implementation of data interaction with the server without refreshing the page.
Role:
Traditional Web pages (do not use Ajax). If you need to update the content, you must reload the entire Web page, and by using Ajax you can perform a small amount of data exchange with the server in the background, enabling the Web page to be updated asynchronously. This means that you can update a part of a webpage without reloading the entire page.
Implementation method
- XMLHttpRequest Object
- Fetch (less compatible than XMLHttpRequest)
Compatibility query
Example Get example
Asynchronous getvar xhr =New XMLHttpRequest () Xhr.open (' GET ','/login?username=evenyao&password=123 ',TrueGet type data need to be stitched into a URL to put in? Back Xhr.send ()Console.log (' ReadyState: ', xhr.readystate) Xhr.addeventlistener (' ReadyStateChange ',function){or use Xhr.onload = function ()View readystate StatusConsole.log (' ReadyState: ', Xhr.readystate)}) Xhr.addeventlistener (' Load ',function){Console.log (Xhr.status)if (Xhr.status >=&& Xhr.status <300) | | Xhr.status = = =304) {var data = Xhr.responsetextConsole.log (data)}else{Console.log (' Error ')}}) Xhr.onerror =function){Console.log (' Error ')}Equivalent codevar xhr =New XMLHttpRequest () Xhr.open (' GET ', '/login?username=evenyao&password=123 ', true) xhr.send ( ) Xhr.onreadystatechange = function ( if (xhr.readystate = = 4) {if ((xhr.status >= 200 && xhr.status < 300) | | Xhr.status = = = 304) {console.log (xhr.responsetext)}else{console.log ( ' ERROR ')}}} Xhr.onerror = function (console.log ( ' error ')}
POST Example
Asynchronous postvar xhr =New XMLHttpRequest () Xhr.open (' POST ','/login ',TruePost stitching data drop send insidePost stitching data drop send inside Xhr.send (Makeurl ({Username' Evenyao ',Password' 123 ')) Xhr.addeventlistener (' Load ',function){Console.log (Xhr.status)if (Xhr.status >=&& Xhr.status <300) | | Xhr.status = = =304) {var data = Xhr.responsetext console.log (data)}else{console.log ( ' ERROR ')}}) Xhr.onerror = Span class= "hljs-function" >function (console.log ( ' error ')}// Makeurl stitching function function MAKEURL ( Span class= "Hljs-params" >obj) {var arr = [] for (var key in obj) {arr.push (key + ' = ' + Obj[key])} Span class= "Hljs-keyword" >return arr.join ( ' & ')}
Encapsulating Ajax
Encapsulating AjaxfunctionAjaxOPTs) {var url = opts.urlIf there is a type, use the type of user input; If not, the default is the followingvar type = Opts.type | |' GET 'var dataType = Opts.datatype | |' JSON 'var onsuccess = opts.onsuccess | |function){}var onerror = Opts.onerror | |function){}var data = Opts.data | | {}Data serializationvar datastr = []Forvar keyIn data) {Datastr.push (key +' = ' + Data[key])} DATASTR = Datastr.join (' & ')Get type using URL stitchingif (type = = =' GET ') {URL + ='? ' + datastr}XMLHttpRequest Object creationvar xhr =New XMLHttpRequest () Xhr.open (Type,url,true) Xhr.onload =function){if (Xhr.status >=&& Xhr.status <300) | | Xhr.status = =304) {SuccessIf the data type returned is JSON, it is parsed into JSON formatif (DataType = = =' json ') {onsuccess (Json.parse (Xhr.responsetext))}else{onsuccess (Xhr.responsetext)}}else{onerror ()}}If the network is disconnected, onerror () Xhr.onerror = OnError () will also be executedPost Typeif (type = = =' POST ') {xhr.send (DATASTR)}else{xhr.send ()}}ajax ({Url:' Http://xxx ',type: ' POST ', data: { ' Beijing '}, onsuccess: function (ret) {console.log (ret) render (ret) }, onerror: function (console.log ( ' server exception ') ShowError ()}) function render ( json) {}function showError (
Reference
Do you really use XMLHttpRequest?
Ajax status values and status codes
about how to mock data http-server
Local use http-server
node tool to start a static server
Here are the Ajax usages that have been written, using the Get type,xhr.open(‘GET‘,‘/hello2.json‘,true)
In the case of already installed node
and http-server
, first cd
to the corresponding folder. Then by http-server
starting the local server.
By accessing and 127.0.0.1:8080/indexl.html
entering the console, you can see the mock results
Specific AJAX Usage Code:
<! DOCTYPE html><Htmllang="EN" ><Head><Metacharset="UTF-8" ><MetaName="Viewport"Content="Width=device-width, initial-scale=1.0" ><Metahttp-equiv="X-ua-compatible"Content="Ie=edge" ><Title>document</Title></Head><Body><ScriptType="Text/javascript" > Ajax GETvar xhr =New XMLHttpRequest () Xhr.open (' GET ','/hello2.json ',true) xhr.send () Xhr.onload =function){Console.log (Xhr.status)if (Xhr.status >=$ && xhr.status < ) | | xhr.status = = 304) { var data = Xhr.responsetext console.log (dat A) Console.log (json.parse (data))}else{ console.log (' ERROR ')}} Xhr.onerror = function ( { Console.log (' error ')} </script></body></ html>
JSON file contents of the Analog interface:
//hello2.json 内容{ "name": "go", "success": true, "data": [ "70", "80", "90", "年代" ]}
GitHub
Write a server on GitHub to mock
Specific and local difference is not small, just need to pay attention to the address of the analog interface, because the domain name is github.com, so the front also need to add the project name, details see github/mocktest inside the README.MD
Test:
GitHub pages
Online mock-up
Using easy-mock.com for mock data
Enter easy-mock.com, login to register account and enter Create project, enter name and create
- Enter the created project
- Select Create Interface
- fill in the Type (get/post), description, and input JSON-formatted content, click Create
- Generate a link, copy the link
Paste the link into the previously written ajax
usage xhr.open(‘GET‘,‘‘,true)
7. Open the page and go to the console to view the mock results
Ajax and Mock data