我正在为我的所有ajax调用添加csrf令牌,但是我在我的ajax调用中传递序列化数据和JSON数据时遇到错误500。 我包含在我的视图页面中,但它无法正常工作并抛出错误。
$("#submit").on('click', function(e) {
e.preventDefault(); // prevent default form submit
if(validateCode()){
$.ajax({
url: 'verifyCode', // form action url
type: 'POST', // form submit method get/post
data: $('#frm').serialize(),
success: function (result) {
result = JSON.parse(result);
if(result.st == 1){
window.location.href="backupCode";
}
else{
$('#validCodeFormat').html("<span style='color:red'>Invalid authentication code.</span>");
}
},
error: function(e) {
}
});
}
});
var json='json={"age":"'+age+'","age1":"'+age1+'","afterTaxincome":"'+aftertaxincome+'","afterTaxincome2":"'+aftertaxincome2+'","annualSave":"'+annualSave+'","annualSave2":"'+annualSave2+'","liqInvest":"'+liqInvest+'","liqInvest2":"'+liqInvest2+'","nonliqassets":"'+nonliqassets+'","nonliqassets2":"'+nonliqassets2+'","totalLia":"'+totalLia+'","totalLia2":"'+totalLia2+'","savingsChange":"'+savingsChange+'","savingsChange2":"'+savingsChange2+'","preference":"'+preference+'","market":"'+market+'","mail":"'+mail+'","investorTypePage":"'+investortype+'"}';
//alert(json);
$.ajax({url: "questions/sendQuestions",
type: "POST",
data: json,
success: function(result){
},
error: function(xhr, status, errMsg) {
alert("error while fetching data from server.\nPlease try again.");
}
});
答案 0 :(得分:0)
您可能需要在AJAX调用之前使用$.ajaxSetup()
:
<script type="text/javascript">
var csrf_token = {TOKEN};
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrf_token);
}
}
});
</script>
我在使用Flask CSRF Protection之前需要这个。