我有一个带有 method=post 的表单。在那个表单中,我有一个图像上传字段,它是 ajax。当 ajax 调用过程中,验证 csrf token 不匹配错误发生。帮助我。这是我的代码..,
<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
标记到这样的元标记(在主布局中,例如:head 部分中的 resources/views/default.blade.php):
<meta name="_token" content="{{ csrf_token() }}"/>
然后使用
$.ajaxSetup
在ajax调用之前:$.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'
})
关于ajax - 如何通过laravel中的ajax调用发送csrf token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34586560/