ajax: a way to request data without refreshing the entire page;
The technical core of ajax is the XMLHttpRequest object;
ajax request process: create XMLHttpRequest object, connect to the server, send requests, and receive response data;
/** * Get ajax object*/function getajaxHttp() { var xmlHttp; try { //chrome, Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { //IE5, 6 xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { //IE7 or above xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } return xmlHttp;}/** * Send ajax request* url--url * methodtype(post/get) * con (true(asynchronous)|false(synchronous)) * parameter(parameter) * functionName(callback method name, no quotes are required, it is called only when it succeeds) * (Note: This method has two parameters, one is xmlhttp, and the other is the object to be processed) * obj needs to go to the object to be processed in the callback method*/function ajaxrequest(url, methodtype,con, parameter, functionName,obj){ var xmlhttp=getajaxHttp(); xmlhttp.onreadystatechange=function(){ // readyState value description // 0, initialization, XHR object has been created, open has not been executed yet // 1, loading, open method has been called, but the request has not been sent yet // 2, loading has been completed, request has been sent // 3, interaction, part of data can be received // status value description // 200: Successful // 404: No file, query or URl found // 500: The server generates an internal error if (xmlhttp.readyState==4&& XHR.status == 200){ // The HTTP response has been fully received before calling functionName(xmlhttp,obj); } }; xmlhttp.open(methodtype,url,con); xmlhttp.send(parameter);}//This is the parameter function createxml(){ var xml="<user><userid>asdfasdfasdf<//userid></user>";//"//"This is not capital V but the escape is the left slash and the right slash return xml;}//This is the parameter function createjson(){ var json={id:0,username:"good person"}; return json;}function c(){ alert("");}//test
ajaxrequest("http://www.baidu.com","post",true,createxml(),c,document);Let's look at another example
ajax({ url: "./TestXHR.aspx", //Request address type: "POST", //Request method data: { name: "super", age: 20 }, //Request parameter dataType: "json", success: function (response, xml) { // Code executed after successful placement}, fail: function (status) { // Code executed after failure placement} }); function ajax(options) { options = options || {}; options.type = (options.type || "GET").toUpperCase(); options.dataType = options.dataType || "json"; var params = formatParams(options.data); //Create - non-IE6 - Step 1 if (window.XMLHttpRequest) { var xhr = new XMLHttpRequest(); } else { //IE6 and below browsers var xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //Receive - Step 3 xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status >= 200 && status < 300) { options.success && options.success(xhr.responseText, xhr.responseXML); } else { options.fail && options.fail(status); } } } //Connect and send - Step 2 if (options.type == "GET") { xhr.open("GET", options.url + "?" + params, true); xhr.send(null); } else if (options.type == "POST") { xhr.open("POST", options.url, true); //Set the content type when submitting the form xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(params); } } //Format parameter function formatParams(data) { var arr = []; for (var name in data) { arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name])); } arr.push(("v=" + Math.random()).replace(".",")); return arr.join("&"); }Let's take a look at the principle
1. Create
1.1. IE7 and above versions support native XHR objects, so you can use it directly: var oAjax = new XMLHttpRequest();
1.2. In IE6 and its previous versions, the XHR object is implemented through an ActiveX object in the MSXML library. Some books have refined three different versions of such objects in IE, namely MSXML2.XMLHttp, MSXML2.XMLHttp.3.0 and MSXML2.XMLHttp.6.0; I feel that it is too troublesome, so I can directly use the following statement to create it: var oAjax=new ActiveXObject('Microsoft.XMLHTTP');
2. Connect and send
2.1. Three parameters of the open() function: request method, request address, and whether to request asynchronously (there are very few synchronous requests, and have not been used yet);
2.2. The GET request method is to submit data to the server through URL parameters, while POST submits data to the server as a send parameter;
2.3. In a POST request, before sending data, the content type of the form submitted must be set;
2.4. The parameters submitted to the server must be encoded by the encodeURIComponent() method. In fact, in the form of the parameter list "key=value", both key and value need to be encoded because they will contain special characters. Every time you request, a string of "v=xx" will be spelled into the parameter list. This is to reject cache, and each time you request it directly to the server.
encodeURI(): used for encoding the entire URI, and will not encode special characters that belong to the URI, such as colons, forward slashes, question marks and pound signs; its corresponding decode function decodeURI();
encodeURIComponent(): is used to encode a part of the URI and encode any non-standard characters it finds; its corresponding decode function decodeURIComponent();
3. Receive
3.1. After receiving the response, the response data will be automatically filled with the XHR object. The relevant attributes are as follows
responseText: The body content returned by the response, of the string type;
responseXML: If the content type of the response is "text/xml" or "application/xml", the corresponding xml data will be stored in this property, which is the document type corresponding to XML;
status: the response HTTP status code;
statusText: Description of HTTP status;
3.2. The readyState property of the XHR object represents the current active stage of the request/response process. The value of this property is as follows
0-Uninitialized, the open() method has not been called yet;
1-Start, open() method is called, send() method is not called;
2-Send, the send() method has been called, and no response has been received;
3-Receive, part of the response data has been received;
4-Complete, all response data has been received;
As long as the value of readyState changes, the readystatechange event will be called (in fact, for logical smoothness, you can put readystatechange after send, because the server is requested during send, and network communication will be conducted, which takes time. It is also OK to specify the readystatechange event handler after send. I usually use this, but for the purpose of standardizing and cross-browser compatibility, it is better to specify it before opening).
3.3. In the readystatechange event, first determine whether the response is received and then determine whether the server successfully handles the request. xhr.status is the status code. The status code starts with 2 and all succeed. 304 means getting from the cache. The above code adds a random number every time the request is requested, so the value from the cache does not need to be judged.
4. Ajax requests cannot be cross-domain!