【问题标题】:How to add CSRF Token to a dynamically generated form by javascript如何通过javascript将CSRF Token添加到动态生成的表单中
【发布时间】:2016-08-29 03:19:15
【问题描述】:
 function populateMatches(id) {
 var url = "/get_matches/?s=" + id;
 $.get(url, function(response) {
     $container = $('.match-list-container');
     var i = 0;

     if (response.length > 0) {
         $container.html("");
         $container.append("<h5>Matches</h5>");
         $.each(response,function(){ 
             $container.append($("<h4>").text(response[i].match_percentile));
             $container.append($("<h6>").text("%"));
             $container.append($("<p>").text(response[i].match.content));
             $container.append('<form action="#" method="POST" id="match-info-form"><input type="checkbox" id="approve">Approve<input type="checkbox" id="discard">Discard<input type="checkbox" id="skip">Skip<br><input type="submit" id="savebutton" value="Save">');
             i++;
         })
     } else {
         $container.html("");
         $container.append("<h5>No Match Found</h5>");
     }
 });
}

populateMatches 是在 点击事件 上调用的函数。 服务器根据被点击的 div 发送一个包含可变数量的对象的响应。

因此,如果响应中存在“n”个对象,我需要动态创建 n 个表单,因此无法在静态 html 文件中创建表单。

但是如何将 CSRF 令牌添加到我的 javascript 文件中的表单中?

我知道可以在html模板表单中简单地写{% csrf_token %},但是在动态生成表单时如何克服这个问题。

附:我不想排除 csrf 验证

【问题讨论】:

    标签: javascript jquery html csrf django-csrf


    【解决方案1】:

    你能简单地将 CSRF 令牌存储为元标记吗?然后抓取并插入响应?

    见:Is it a good practice to store the csrf token in meta tag?

    【讨论】:

      猜你喜欢
      • 2020-11-21
      • 2019-01-22
      • 2019-11-30
      • 1970-01-01
      • 2015-08-14
      • 1970-01-01
      • 2018-05-27
      • 2012-11-30
      • 1970-01-01
      相关资源
      最近更新 更多