创建 Javascript 库只是为了减少重写目的

Create Javascript Library only for less re-writing purpose?

本文关键字:重写 Javascript 创建      更新时间:2023-09-26

如何创建一个简单的JavaScript库,只是为了不一直编写函数?

例如,对于Jquery的ajax,我必须使用以下内容:

$.ajax({ url: xxx,
         type: xxx,
         dataType: 'json',
         data: xxx,
         success : function(data){
         }
       })

我希望能够做一些像getajax(url,type,success function)或postajax(url,type,data,success function)这样的事情。

这可能吗?我目前有两个三个问题1. 创建库似乎工作量很大?(我是新来的,不能把它们打包在一起,放在.js里再导入吗?2. 如何传递 jquery ajax 在成功时执行的函数?3. 我可以在图书馆中包含库吗?

非常感谢,我是Javascript的新手,有很多类似的网站需要基于相同的格式完成。

彼得

正如我在评论中提到的,jQuery已经为此提供了两种方法。

$.post(URL,data,callback);
$.get(URL,callback);

并回答您关于扩展jQuery以具有更多功能的第二个问题

$.extend({
    myPlugin: function (someVar) {
        // do something here, in this case we'll write to the console
        console.log(someVar);
    }
});
$.myPlugin("Some Text");

我只想回来回答我自己的问题,因为我没有得到以前想要的帮助。使用 jQuery post 和 get Ajax 函数,它不会处理错误。因此,只需创建另一个.js文件,然后添加以下内容并将其包含在您的 html 中。

function getAjax(PageName, Action, Variables, dofunction) {
    $.ajax({
            url : PageName+'/'+Action+'?'+Variables,
            type : "GET",
            dataType : "json",
            success : dofunction,        
            error : function (xhr, ajaxOptions, thrownError) {
                    errLogin(xhr, ajaxOptions, thrownError);
                }
    });
}

function postAjax(PageName, Action, Variables, Data, dofunction) {

    $.ajax({
            url : PageName+'/'+Action+'?'+Variables,
            type : "POST",
            dataType : "json",
            data : Data,
            success : dofunction,        
            error : function (xhr, ajaxOptions, thrownError) {
                    errLogin(xhr, ajaxOptions, thrownError);
                }
    });

}