一遍又一遍地将相同的选项传递给jQuery函数 [英] Pass the same options to a jQuery function over and over

查看:68
本文介绍了一遍又一遍地将相同的选项传递给jQuery函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此jQuery Ajax-Request,它是根据我的需要配置的:

I use this jQuery Ajax-Request, which I configured for my needs:

jQuery.ajax({
    url: "apiBridge.php?url=" +  encodeURIComponent(url),
    headers: {
        "Some Weird Header": "123"
    },
    success: function(data){

    },
    complete: function(){
        doAlotOfStuff();
        andMore();
    }
});

真正的代码相当冗长,每次我需要以自己的样式进行Ajax请求时,我都认为复制/粘贴整个内容很愚蠢.

The real code is fairly lengthy and I consider it stupid to copy/paste the whole thing every time I need to make an Ajax-request in my style.

我想做的是一次定义此函数,因此我可以重复使用它.对于函数的每个实例,我需要更改的只是 url success 回调.

What I want to do, is to define this function once, so I am able to re-use it. All I need to change for each instace of the function is the url and success callback.

正确的方法是什么?

推荐答案

定义一组标准选项:

var ajaxOpts = {
    headers:{},
    url:"someUrl",
    complete:function(){//whatever;},
    otheroptions:"asneeded"
};

进行每个ajax调用时,请使用标准选项扩展本地选项对象:

When you make each ajax call, extend the local options object with the standard options:

$.ajax($.extend({url:"custom", success:doAThing}, ajaxOpts));

...或如@gdoron所述,使用ajaxSetup.我更喜欢$ .extend,因为那样我不会破坏我可能无法控制的页面上的其他$ .ajax调用.

...or as @gdoron says, use ajaxSetup. I prefer $.extend because that way I'm not clobbering other $.ajax calls on the page I might not control.

这篇关于一遍又一遍地将相同的选项传递给jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆