CP from:https://www.codercto.com/a/9839.html
Mock.js can simulate Ajax data, block AJAX requests, return analog data, and test front-end programs without back-end
Introducing Files
First, we'll introduce the Mockjs file we need in head.
<script src= "//upyun1.codercto.com/images/1x1.png" data-original= "Http://mockjs.com/dist/mock.js" ></ Script>
Defining data
Use Mack to define the return data before the AJAX request
Mock.mock (' Http://laoyu ', {"errorcode": 0,//0 for Success, 1 for error "message": "XX Information incomplete"//Popup error message});
Create request
In Ajax, the URL of open () is the same as in a mock, as I am here http://laoyu
, so
Xhr.open ("Post/get", "Http://laoyu", True/false)
Test
Okay, here we are, let's test it.
<script>//call the mock method to simulate the dataMock.mock (' Http://laoyu ', { "ErrorCode": 0,//0 indicates success, 1 indicates error"Message": "XX information is incomplete",//Pop-up error message}); //using Ajax for testingvarXHR =NewXMLHttpRequest (); Xhr.open ("Post", "Http://laoyu",true); Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); Xhr.send (NULL); Xhr.onreadystatechange=function(){ if(Xhr.readystate = = 4){ if((xhr.status>=200 && xhr.status<300) | | xhr.status== 304){ vardata = Json.parse (Xhr.responsetext);//because Reponsetext returns a string, the string is converted to the JSON data we want, so we can call theconsole.log (data); //print out the returned content in the console}Else{alert ("Request was unsuccessful:" +xhr.status); } }}</script>
See, we've returned the data we used with mock simulations, so we can do our own testing without the background.
Five states of the Xhr.readystate
0-(uninitialized) has not yet called open () Method 1-(The server connection has already been established) has called the Open () method, is sending a request 2-(request received) the Send () method execution completes, has received the full response Content 3-(Request processing) is parsing the response content 4-(Request has been Completion), the response content resolution is completed and the client can call the
Links: https://www.codercto.com/a/9839.html
Source: Coder yards Farm
This article is published in Coder yards, reproduced please indicate the source, thank you for your cooperation!
[Web front end] MOCKJS enables front-end development to be independent of the backend