-1

我怎样才能创建一个简单的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 新手,有很多类似的网站需要基于相同的格式完成。

彼得

4

2 回答 2

5

正如我在评论中提到的,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");
于 2013-11-01T09:07:14.530 回答
0

我只想回来回答我自己的问题,因为我没有得到我之前正在寻找的帮助。使用 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);
                }
    });

}

函数 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);
                }
    });

}

于 2013-11-08T11:51:44.127 回答