JS-simple application of callback functions (episode)
JS is undoubtedly a powerful language for front-end pages to interact with the server. How can we use JS callback functions to encapsulate JS network requests? This article will briefly describe this problem.
Create an index.html File
The page content is customized. The focus is to introduce the following two custom js files: constants. js and validate. js.
2. Create a constants. js File
/*** Created by liuyazhuang on 2015/5/29. * This file encapsulates the URLs of some network access requests, * encapsulates the usage of some callback functions and some constants * // lyz server var base_url_lyz_server = http: // 192.168.254.109: 10002/tea; // var base_url_lyz_img_server = http: // 192.168.254.109: 10002; // postvar REQUEST_TYPE_POST = POST; // GETvar REQUEST_TYPE_GET = GET; // concatenate a string // The specific interface path except the basic path of the uri // isValidate indicates whether logon is required. If this parameter is set to true, logon is required. If the parameter is set to false, you do not need to log on to function getUrl (uri, isValidate) {var url = ba Se_url_lyz_server + uri; if (isValidate) {var token = getValueFromLocalStorage (token); var username = getValueFromLocalStorage (phone); url = url +? Access_token = + token + & mobile_user_name = + username;} return url;} // function getImgUrl (uri) {return base_url_native_img_server + uri of the image path ;} // obtain a value in localStorage function getValueFromLocalStorage (key) {return localStorage. getItem (key )? LocalStorage. getItem (key) :;}// remove the specified keyfunction removeValuesFromLocalStorage (keys) {for (var I = 0; I <keys. length; I ++) {localStorage. removeItem (keys [I]);}/*** encapsulated ajax request data * url: Request Path * params: parameter * isValidate: whether logon verification is required * type: access type: POST, GET, * method: callback method name */function requestDataByAjax (url, isValidate, params, type, method) {$. ajax ({type: type, url: getUrl (url, isValidate), cache: false, async: false, data: {parameter: params}, success: function (result) {// method (result);}, error: function (XMLHttpRequest, textStatus, errorThrown) {alert (error: + textStatus );}});}
In this js file
The underlined part is the name of the callback function to be called after the network request returns the successful data. This method can be called for all services related to the network request, the data returned by the server can be parsed by the corresponding callback function, which not only reflects the code encapsulation, but also greatly improves the code maintainability.
3. Create validate. js
// Request address requestDataByAjax (/website/address/default_address, true, JSON. stringify ({mobile_id: userId}), REQUEST_TYPE_POST, validate_parseAddressResult); // The callback method parses the address data function validate_parseAddressResult (result) {// The data returns to the normal console. log (result); if (result. code == 1001) {var message = result. message; $ (# appointment_name ). text (message. name); $ (# appointment_phone ). text (message. phone); $ (# appointment_address ). text (message. address); localStorage. setItem (sendName, message. name); localStorage. setItem (sendPhone, message. phone); localStorage. setItem (sendAddress, message. address );}}
In this js File
The name of the underlined part is the same, and constants is called. the requestDataByAjax method of js uses the name of the method function validate_parseAddressResult (result) as the parameter. When the network request returns data successfully, the function validate_parseAddressResult (result) is automatically called to parse the data.
Iv. Test