简体   繁体   中英

JavaScript AJAX, xmlHttpRequest in seperate class

so my plan is to have your normal JavaScript working with html to create and dynamically change your webpage. But instead of having and creating the xmlhttp object with the different functions inside the same class I want to create one in a separate class so that it can be used with any class. I am trying to find examples on how to do this but everyone seems to create it and use it the same class. So in the xmlRequest class I would have something like this function() create new xml object

onError() when and if error occurs

success() the content has been retrieved and loaded

I just don't understand how to make this work with any other separate class.

This is an example of an "ajax service" i'm using in my projects, you can do something like it(and i recommend using Axios as in this example)

import axios from 'axios';    


class AjaxService {//Simple wrapper for Axios, in order to manually handle errors which aren't 500

    /**
     * NOTE: This is NOT an abstraction layer, but just a wrapper for Axios. All consuming modules should expect Axio's response format(response.data). 
     * @public
     * @param {string} url 
     * @param {Object} config 
     */
    static async post(url, config) {       
        return await this.shootAjax('post',url, config);

    }   


    /**
     * @public
     * @param {string} url 
     * @param {Object} config 
     */
    static async get(url, config) {

       return await this.shootAjax('get',url, config);            

    }

    /**
     * @public
     * @param {string} key 
     * @param {string} value 
     */
    static setHeader(key,value){
        axios.defaults.headers.common[key] = value;
    }    

    /**
     * @private
     * @param {string} method 
     * @param {string} url 
     * @param {Object} config 
     */

    static async shootAjax(method, url, config) {
        // debugger;
        // url = this.processUrl(url);
        let response;
        if (method === 'get') {
            response = await axios.get(url, config);
        } else {
            response = await axios.post(url, config);
        }

        if (response.data.status !== 'ok') {//Manual promise rejection.
            const error = new Error(response.data.error);
            error.errorCode = response.data.errorCode;
            throw error;
        }
        return response;
    }
}

export default AjaxService;

Note that in this example i have some manual error handling according to the structure of my API responses, of course you could setup your own.

With this approach, all you need to do in the "upper code" is to await the get/post functions, inside a try/catch block.

You need a framework to manage your dependencies, like RequireJs. which is used to loads the JavaScript files, it is a framework to manage dependencies between JavaScript files, and in modular programming, all the functionality divides in different modules, so RequireJs is a best tool to assemble different JavaScript files from different modules by which it helps to improve speed and quality of your code. CommonJs is another framework that can be used in similar way.

Here is a basic usage of RequireJs: RequireJs for CommonJs that is basically the same thing as require CommonJs

Another option is if you are using javascript ES6 is to implement export/import in each module. You export the module and import it to the module you want to access to its methods.

Here is documentation Import/Export ES6 Modules

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM