AJAX = Asynchronous JavaScript and XML, AJAX is a technique for creating fast, dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server in the background. This means that part of a web page can be updated without reloading the entire page.

1. The XMLHttpRequest object

XMLHttpRequest is the foundation of AJAX and is used to exchange data with the server in the background. All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects (IE5 and IE6 use ActiveXObject).

(1) Create XMLHttpRequest object

variable_name = new XMLHttpRequest(); To deal with all modern browsers, including IE5 and IE6, check that your browser supports the XMLHttpRequest object. // Create an XMLHttpRequest object if it is supported. If not, create ActiveXObject: var XMLHTTP; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }Copy the code

(2) Send a request to the server

Using the XMLHttpRequest object’s open() and send() methods:

xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
Copy the code

Open (method, URL,async) specifies the request type, URL, and whether to process the request asynchronously.

  • Method: Request type. GET or POST
  • Url: The location of the file on the server
  • Async: true (asynchronous) or false (synchronous)

Send (string) Sends a request to the server.

  • String: Used for POST requests only

(3) GET or POST?

Compared to POST, GET is simpler and faster, and works in most cases.

However, use a POST request in the following cases:

  • Unable to use cached files (updating files or databases on the server)
  • Sending large amounts of data to the server (POST has no data limit)
  • POST is more stable and reliable than GET when sending user input that contains unknown characters

(4) Get request

Send requests and receive data

Xmlhttp. open("get","example.txt",false) // Synchronize request xmlhttp.send(null)Copy the code

Synchronize the request, and the javascript code waits until the server responds.

Upon receipt of the response, the response data is automatically populated with the attributes of the XMLHTTP object, which are summarized below:

  • ResponseText: The text returned by the response body to get the response data as a string.
  • ResposeXML: The text returned by the response body to get the response data in XML form.
  • Status: indicates the HTTP status of the response

The response

if(xmlhttp.status>=200 && xmlhttp.status<300 || xml.status == 304){ alert(xmlhttp.resposeText); // Use the response data}Copy the code

For asynchronous requests, use the readyState property of the XMLHTTP object, which represents the current active phase of the request/response process.

  • 0: not initialized
  • 1: starts, and the open() method executes
  • 2: sends. The send() method is executed
  • 3: receives. Some response data has been received
  • 4: Complete. All response data has been received and can be executed on the client

Changing the value of the readyState property from one value to another triggers a readyStateChange event, and you can use the onReadyStatechange method to define response handling. It should be noted that the onReadyStatechange event handler must be specified before calling the open() method

xmlhttp.onreadystateschange = function(){ if(xmlhttp.readtState == 4){ if(xmlhttp.status>=200 && xmlhttp.status<300 || xml.status == 304){ alert(xmlhttp.resposeText); // Use response data}}} xmlhttp.open() xmlhttp.send()Copy the code

(5) post request

xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
Copy the code

JQuery encapsulates AJAX

Vue send Ajax

1. Introduction

Vue itself does not support Ajax requests. Plug-ins such as VUe-Resource and AXIos need to be used. Axios is a Promise-based HTTP request client that sends requests and is an official vue2.0 recommendation. Vue-resource is not updated since Vue2.0.

Github address: github.com/axios/axios

Using the API: www.kancloud.cn/yunye/axios…

2. Use AXIos to send AJAX

The installation

$ cnpm install axios -s
$ cnpm install vue-axios --s
Copy the code

use

<! --main.js--> import Vue from 'vue' import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(axios, VueAxios)Copy the code

Add axios and vue-Axios relationship

Axios is a library, not a third party plug-in in Vue. It cannot be used through vue.use () and needs to be bound to the prototype.

import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$http = axios
Copy the code

Vue-axios is a small wrapper that integrates AXIOS into vue.js and can be installed like a plug-in: used as above.

On the NPM vue – axios explanation: www.npmjs.com/package/vue…

Use mock. js to intercept Ajax requests

Reference:

  1. Vue’s simple use of mocks. www.cnblogs.com/l-y-h/p/116…
  2. The Mock. Js’s official website. Github.com/nuysoft/Moc…

1. Introduction

Mock is a mock data generator designed to help the front end develop independently of the back end and to help write unit tests. It simulates Ajax and returns simulated data. Main functions: Generate random data and intercept Ajax requests

2. Installation (based on VUE)

cnpm install mockjs
Copy the code

Use 3.

// Create a new mock.js file and introduce mockjs
var Mock = require('mockjs')
Copy the code

The main API

/* Records the function used to generate the response data. When an Ajax request matching rURL and RType is intercepted, the function(options) is executed and the result is returned as response data. */ Mock. Mock (rurl, rtype, function(options)) rurl, optional. Indicates the URL to be intercepted. It can be a URL string or A URL re. For example /\/domain\/list\. Json/and '/domian/list.json'. Rtype optional. Represents the type of Ajax request to intercept. For example, GET, POST, PUT, and DELETE. An optional function (options). Represents the function used to generate the response data.Copy the code

supplement

You can also mock data using lines

  1. Use easy-mock.com
  2. Using rapapi.org/org/index.d…

Vue front-end server proxy, proxytable brief description

Reference: www.cnblogs.com/wasbg/p/126…

File location: config/index.js. If you change the configuration item file, restart the server

//proxyTable configuration description
proxyTable: {
    // Set the '/ API 'equivalent to target. You can access/API === http://localhost:54321 in the link
    '/api': {
        target: 'http://localhost:54321/'./ / the real server interface address / / http://localhost:54321/json.data.json,
        secure: true.// If HTTPS is used, this option needs to be enabled
        changeOrigin: true.// Is it a cross-domain request? Yes, there is no need to configure the proxyTable without cross-domain.
        pathRewirte: {
          // This is an append link. For example, if the interface contains/API, this configuration is required.
          '/^api': 'api/'./ / equivalent to the
          // step 1 /api = http://localhost:54321/
          // step 2 /^api = /api + api == http://localhost:54321/api}}},Copy the code