With the XMLHttpRequest object
1, New Object
2, to establish a connection
3, the transmission request
4, view status of the request to receive data back
Send a get request:
var xhr = new XMLHttpRequest (); // Step: New Object xhr.open ( 'GET', 'url', true); // Step: open connection request parameter written in the url xhr.send (); // third step: sending a request in the write parameter in the URL /** * Handler after acquiring data */ httpRequest.onreadystatechange = function () { if (httpRequest.readyState == 4 && httpRequest.status == 200) { var res = httpRequest.responseText; // acquired json string, parses } };
Send a post request:
var xhr = new XMLHttpRequest (); // Step: New Object xhr.open ( 'POST', 'url', true); // Step: open connection xhr.setRequestHeader ( "Content-type", "application / x-www-form-urlencoded"); // Set request header Note: post request header mode must be set (setting request after establishing a connection head) httpRequest.send ( 'name = teswe & ee = ef'); // send a request to send in the case of the write head body /** * Handler after acquiring data */ xhr.onreadystatechange = function () {// callback interface after the request, the request logic may be successfully if (httpRequest.readyState == 4 && httpRequest.status == 200) {// verification request sent successfully var res = httpRequest.responseText; // Get the data returned from the server } };
json post request data:
var xhr = new XMLHttpRequest (); // Step: New Object xhr.open ( 'POST', 'url', true); // establish a connection xhr.setRequestHeader ( "Content-type", "application / json"); // Set request header Note: post request header mode must be set (setting request after establishing a connection head) var obj = { name: 'zhansgan', age: 18 }; xhr.send (JSON.stringify (obj)); // send a request to send the write json /** * Handler after acquiring data */ httpRequest.onreadystatechange = function () { if (httpRequest.readyState == 4 && httpRequest.status == 200) { } };