"Vue.js combat exercises try to do a book p231

Exercise: Learning XMLHttpRequest (ie XHR) related knowledge, develop a simple plug-in ajax, asynchronous won
fetch server data.

answer:

Author of the book provides a piece of code as a reference, actually requires us to encapsulate this code, this plugin provides two interfaces: get and post, accepts a string argument: url

the install = const function (Vue, Options = {}) { 
   // helper function for creating an object xhr added readystatechange event handler
function createXhr () { const xhr = new new the XMLHttpRequest (); xhr.onreadystatechange = function () { IF (xhr.response ===. 4 ) { const Status = xhr.status; IF (Status> 200 is && Status = <300 ) { options.success && options.success (the JSON.parse (xhr.responseText), xhr.responseXML ); } the else { options.error && options.error (Status); } } }; return XHR; }   // helper function for transmitting to the server-creating data Data function createData () { const Data = []; for (the let I in options.data) { data.push (the encodeURIComponent (I) + '=' + the encodeURIComponent (options.data [I])); } Data = data.join ( '&' ); return Data; } const Ajax =new new Vue ({ Methods: {
       // Interface 1, to accept the url parameter, GET (url) { const XHR
= createXhr (); const Data = createData (); xhr.open ( 'the GET', url + + Data '?' , to true ); xhr.send ( null ); },
        // 2 the interface, accepts the url parameter POST (url) { const XHR
= createXhr (); const Data = createData (); xhr.post ( 'the POST', url, to true ); xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-rulencoded' ); xhr.send(data); } } }); Vue.prototype.$ajax = ajax; }; export default install;

 

Guess you like

Origin www.cnblogs.com/sx00xs/p/11403250.html