覆盖所有来自javascript的请求

Override all requests from javascript

本文关键字:javascript 请求 覆盖      更新时间:2023-09-26

我有一个asp.net应用程序。我需要实现,每个请求服务器的页面将包含一个额外的参数在查询字符串。我的想法是在javascript中捕获所有请求并添加此参数。

我可能会使用jQuery选择器的每一个链接,并改变它的href和重写jQuery ajax添加这个参数的请求,但这不是最好的解决方案。

这在JS中是可能的吗?

谢谢,Bartek

您可以为页面上的每个链接添加事件处理程序:

//use jQuery 1.7's `.on()` to bind the event handler
$('a').on('click', function (e) {
    //stop the default click from happening
    e.preventDefault();
    //setup the extra query-string parameter
    var extra = '?your_extra=true';
    //if the link clicked already has a query-string then use an ampersand rather than a question mark
    if (this.href.indexOf('?') > 0) {
        extra = '&your_extra=true'
    }
    //direct the user to the requested page
    window.location = this.href + extra;
});

您可以使用beforeSend函数在AJAX请求发送之前更改它们:http://api.jquery.com/jquery.ajax/

对于锚标记,它就像;

$(document).delegate('a', 'click', function() {
    this.href = (this.href.indexOf("?") > -1 ? '&' : '?') + 'magicParam=4';
});

如果你使用的是jQuery 1.7,你可以这样做;

$(document).on('click', 'a'function() {
    this.href = (this.href.indexOf("?") > -1 ? '&' : '?') + 'magicParam=4';
});

如果你想要考虑表单、AJAX请求等,你必须单独管理它们。当然,如果你有一个window.location.href = blahblahblah,这些也不会被满足。

如果你想处理AJAX请求,jQuery有一个很好的beforeSend方法,你可以添加到你的jQuery.ajaxSetup来修改所有的url的目标。