创建 Javascript 库只是为了减少重写目的
Create Javascript Library only for less re-writing purpose?
如何创建一个简单的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);
}
});
}
相关文章:
- 如何重写Javascript If语句以选择Classes而不是ID's的HTML格式
- 在类外重写Javascript方法,使用默认行为
- 重写javascript函数定义
- 重写javascript函数
- 重写/重写javascript库函数
- 单击按钮时重写javascript变量值
- 用函数重写Javascript属性
- 重写JavaScript中的Object.create方法
- 重写Javascript's to字符串表示数字
- 重写javascript方法enable
- 如何使用php重写javascript函数
- 无法重写 JavaScript 对象的属性
- 重写 Javascript 方程
- 重写Javascript中的window.close
- 破解/重写Javascript
- 用另一个对象重写Javascript Whole Date对象
- 得到“;未定义的“;在重写Javascript中的_.find函数时
- 重写javascript函数(Drupal中的Superfish)
- 重写Javascript中的默认函数
- 重写Javascript中的方法