如何通过laravel中的ajax调用发送csrf令牌? [英] how to send csrf token through ajax call in laravel?
本文介绍了如何通过laravel中的ajax调用发送csrf令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有method = post的表单.在那个表单中,我有一个图像上传字段,它是ajax.当ajax调用过程出现时,请验证csrf令牌不匹配错误.>
i have a form with method=post.In that form i have an image upload field which is ajax.when the ajax call process,verify csrf token mismatch error occure.help me.this is my code..,
<script>
$(document).ready(function(){
$(document).on("click", "#upload", function() {
var file_data = $("#groupe_img").prop("files")[0]; // Getting the properties of file from file field
var form_data = new FormData(); // Creating object of FormData class
form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
form_data.append("csrftoken",document.mainform.csrftoken.value;) // Adding extra parameters to form_data
$.ajax({
url: "/upload_avatar",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post'
})
})
});
</script>
这是我的html部分
<input type="file" name="groupe_img" id="groupe_img">
<button id="upload" value="Upload">upload image</button>
暴虐
推荐答案
首先将 csrf
令牌添加到这样的元标记(例如,在主布局中为,例如:resources/views/default.head.中的blade.php ):
First add csrf
token to a meta tag like this (in main layout for example: resources/views/default.blade.php in head section):
<meta name="_token" content="{{ csrf_token() }}"/>
然后在进行ajax调用之前使用 $.ajaxSetup
:
Then use $.ajaxSetup
before ajax call:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: "/upload_avatar",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post'
})
这篇关于如何通过laravel中的ajax调用发送csrf令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文