javascript jQuery ajax 在特定 url 上在发送之前覆盖数据/url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17848353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:51:21  来源:igfitidea点击:

jQuery ajax overwrite data/url beforeSend on specific url

javascriptajaxjquery

提问by Chia-Yu Pai

Question

问题

I wanna set a ajax setting for global ajax handled by jQuery

我想为 jQuery 处理的全局 ajax 设置一个 ajax 设置

Condition:

状况:

If ajax url is 'www.example.com', the data (querystring or body) will append token.

如果 ajax url 是“www.example.com”,数据(查询字符串或正文)将附加令牌。



I tried two method

我尝试了两种方法

.ajaxPrefilter

.ajax前置过滤器

$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {

    // Add data to ajax option
    if (options.url.match(/www\.example\.com/i) !== null) {
        originalOptions.data.token = 'i_am_token'
    }

});

To add token when url is www.example.com-> it not work!

在 url 为 www.example.com-> 时添加令牌不起作用!

In console/debugger originalOptions Object is added token property, but request sent not having token parameter

在控制台/调试器 originalOptions 对象中添加了令牌属性,但发送的请求没有令牌参数

.ajaxSetup / beforeSend Event

.ajaxSetup / beforeSend 事件

$.ajaxSetup({
    beforeSend: function(jqXHR, settings) {

        // Only GET Method
        if (settings.url.match(/www\.example\.com/i) == null){
            settings.url.replace(/((\.\/[a-z][0-9])*\?+[=%&a-z0-9]*)&?token=[a-z0-9]*&?([=%&a-z0-9]*)/gi, "")
        }

    },
    data: {
        token: 'i_am_token'
    }
});

And a reverse resolution, add token for each ajax request.

还有一个反向解析,为每个ajax请求添加token。

Same as last one, settings.url changed by string replace in the console/debugger. But request still sent original url.

与上一个相同,settings.url 通过控制台/调试器中的字符串替换更改。但请求仍然发送原始网址。



Test in jsfiddle: http://jsfiddle.net/qVLN2/2/

在 jsfiddle 中测试:http: //jsfiddle.net/qVLN2/2/

Thanks for your reading and help :)

感谢您的阅读和帮助:)

采纳答案by alexcasalboni

You should notice that the String.replacefunction doesn't affect the original string!

您应该注意到String.replace函数不会影响原始字符串!

You can try using settings.url = settings.url.replace(....);in your code.

您可以尝试settings.url = settings.url.replace(....);在代码中使用。