Encapsulation of basic Ajax tutorials 3 (3) and 3
In the previous article, I introduced the Ajax basic tutorial (1) Ajax basic tutorial (2)
Today, let's talk about the chestnuts in the previous blog post. Now I want to expand the demand. I used to click the button to get news. Now I want to update the news every other time. At this time, a timer must be added, and then an Ajax request is made every other time. Since Ajax requests are frequently used, it is necessary to encapsulate functions, let's take a look at the js Code of the previous Chestnut and encapsulate it.
Window. onload = function () {var oBtn = document. getElementById ('btn '); oBtn. onclick = function () {var xhr = null; if (window. XMLHttpRequest) {xhr = new XMLHttpRequest ();} else {xhr = new ActiveXObject ('Microsoft. XMLHTTP ');} xhr. open ('get', 'getnews. php', true); xhr. send (); xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200) {// The task var data = JSON is successfully executed in red. parse (xhr. responseText); // convert the content obtained in the background to json type. Each json contains two keys: title and datevar oUl = document. getElementById ('ul1'); // obtain the node var html = ''; for (var I = 0; I <data. length; I ++) {// loop all json data, add each entry to the list in html + = '<li> <a href = "">' + data [I]. title + '</a> [<span>' + data [I]. date + '</span>] </li>';} oUl. innerHTML = html; // place the content in the page} else {alert ('error, Err:' + xhr. status) ;}}}}</script>
The main point of a function encapsulation is to extract the repeatedly used parts and take some changed things as parameters, which cannot be judged and processed as parameters.
1. Let's first look at the changes: 1. The request method is get/post 2. The request address is 3. The request data is 4. What needs to be done after the request is successful.
Therefore, these four parameters are used as function parameters: ajax (method, url, data, success );
2. Because different request methods have different data transmission methods, conditional judgment is required for these methods.
3. Another question is about xhr. responseText, the variable xhr is declared in the encapsulation function, so this is an ajax function, which we cannot use in the success function, but the success function needs to use this data. Therefore, when the success function is called in the encapsulation function, xhr. responseText is used as the parameter for outgoing. Success (xhr. responseText ).
In fact, this is a callback. A callback is a function that acts as a parameter of another function and is called in another function. success is used as a parameter of the ajax function, and called in ajax. (In fact, I personally think that the function is using parameters. The function parameters are used, but now the parameters are functions, so I will call them ).
So the encapsulation is like this:
Function ajax (method, url, data, success) {var xhr = null; try {xhr = new XMLHttpRequest ();} catch (e) {xhr = new ActiveXObject ('Microsoft. XMLHTTP ');} if (method = 'get' & data) {url + = '? '+ Data;} xhr. open (method, url, true); if (method = 'get') {xhr. send ();} else {xhr. setRequestHeader ('content-type', 'application/x-www-form-urlencoded'); xhr. send (data);} xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200) {success & success (xhr. responseText); // If a function exists, execute the following & execution process, that is, the previous execution is true before execution .} Else {alert ('error, Err:' + xhr. status );}}}}
The call is like this.
ajax('get','getNews.php','',function(data) {var data = JSON.parse( data ); var oUl = document.getElementById('ul1');var html = '';for (var i=0; i<data.length; i++) {html += '<li><a href="">'+data[i].title+'</a> [<span>'+data[i].date+'</span>]</li>';}oUl.innerHTML = html;});
In fact, this encapsulation is not so good. For example, if there is no data in the data above, we still need to place a placeholder. For example, it is easier to transmit parameters in json format in jquery. It is not summarized yet, supplement later.