简体   繁体   English

单独类中的 JavaScript AJAX、xmlHttpRequest

[英]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.所以我的计划是让您的普通 JavaScript 与 html 一起使用来创建和动态更改您的网页。 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.但是,我不想在同一个类中使用不同的函数创建 xmlhttp 对象,而是想在一个单独的类中创建一个对象,以便它可以与任何类一起使用。 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所以在 xmlRequest 类中,我会有类似这样的函数()创建新的 xml 对象

onError() when and if error occurs onError() 发生错误时

success() the content has been retrieved and loaded success() 内容已被检索并加载

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)这是我在我的项目中使用的“ajax 服务”的一个例子,你可以做类似的事情(我建议在这个例子中使用 Axios)

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.请注意,在此示例中,我根据 API 响应的结构进行了一些手动错误处理,当然您可以设置自己的。

With this approach, all you need to do in the "upper code" is to await the get/post functions, inside a try/catch block.使用这种方法,您需要在“上层代码”中做的就是在 try/catch 块内等待 get/post 函数。

You need a framework to manage your dependencies, like RequireJs.您需要一个框架来管理您的依赖项,例如 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.用于加载 JavaScript 文件,它是管理 JavaScript 文件之间依赖关系的框架,在模块化编程中,所有功能都划分在不同的模块中,因此 RequireJs 是从不同模块组装不同 JavaScript 文件的最佳工具,它通过它有助于提高代码的速度和质量。 CommonJs is another framework that can be used in similar way. CommonJs 是另一个可以以类似方式使用的框架。

Here is a basic usage of RequireJs: RequireJs for CommonJs that is basically the same thing as require CommonJs下面是 RequireJs 的基本用法: RequireJs for CommonJs 与 require CommonJs基本相同

Another option is if you are using javascript ES6 is to implement export/import in each module.另一种选择是,如果您使用的是 javascript ES6,则在每个模块中实现导出/导入。 You export the module and import it to the module you want to access to its methods.您导出模块并将其导入到要访问其方法的模块中。

Here is documentation Import/Export ES6 Modules这是文档导入/导出 ES6 模块

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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