【问题标题】:Possible to add argument to all jQuery post calls?可以为所有 jQuery post 调用添加参数吗?
【发布时间】:2013-10-06 17:16:23
【问题描述】:

我有一个应用程序,我通过要求对服务器的所有请求都包含一个 CSRF 令牌来实现 CSRF 保护。我的应用程序中有很多地方使用 jQuery post 函数,如下所示:

$.post("/ajax/whatever", {data: "my data"}, function(data){
   //whatever
});

除非我包含如下 CSRF 令牌,否则上述请求将不起作用:

$.post("/ajax/whatever", {data: "my data", _csrf: "my_csrf_token"}, function(data){
   //whatever
});

不幸的是,这需要我修改使用post 函数的每一段代码。

我想知道是否有任何方法可以拦截对 post 函数的所有调用并更新传递的数据以包含丢失的 CSRF 令牌?这可以做到吗?关于从哪里开始的建议?

【问题讨论】:

  • 有一个全局 ajaxSend 处理程序,但我不确定它是否会让您修改 ajax 选项。
  • 另见Post

标签: jquery ajax security csrf


【解决方案1】:

重写 JQuery 函数真的很容易;-)

var CSRF ="123456789";

(function(jQuery){
  var oPost = jQuery.post;
  jQuery.post = function( ) {
        if (!jQuery.isFunction( arguments[1] )) {
            arguments[1]['_csrf'] = CSRF;   
        }
    return oPost.apply($, Array.prototype.slice.apply(arguments));
  };
})(jQuery)

this

【讨论】:

  • hrrm 是否可以有一个覆盖,只更新数据并调用原始的 post 函数?
猜你喜欢
  • 1970-01-01
  • 2022-08-22
  • 1970-01-01
  • 2013-07-18
  • 2016-07-13
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多