我正在 Spring 3.x 中使用 CSRF。在 Jquery 调用时,需要在 requesetHeader 中设置 token ,否则会出现 CSRF“null”异常。因此,我尝试获取 javascript 函数中的值,并能够获取 javascipt 函数内的 token 值和 header 值,然后我尝试使用以下功能设置 token ,但没有一个起作用。
方法一:
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$.post(
url,
beforeSend: function(xhr){
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","application/json");
},
$(testform).serialize(),
function(data) {
async: false;
}).done(function(data){
});
方法2:
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$.post(
url,
headers: {header,token},
$(testform).serialize(),
function(data) {
async: false;
}).done(function(data){
});
请提出建议或帮助我解决这个问题。
使用以下代码更新,
方法3:
从下面的代码中,我能够成功地访问 Controller ,但响应不会转发到另一个 jsp。我是否遗漏了以下代码中的任何内容,请建议我。
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$.post(
url,
{_csrf_header : header, _csrf : token},
$(testform).serialize(),
function(data) {
async: false;
}).done(function(data){
});
最佳答案
var csrf = $('input[name="_csrf"]').val();
var contentResult=document.getElementById('divComboProductos');
var comercio =$("#ddlComercio").val();
$.ajax({
url: [[@{'/comun/productos/obtener/'}]] + comercio,
data: { _csrf : csrf},
dataType:'text',
cache:false,
type:'POST',
success:function(response){
contentResult.innerHTML=response;
}
});
关于jquery - 如何在 requestheader 中设置 CSRF token 以传入 $.post 方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22834428/