javascript - 使用 Ajax 和 formData 的 Laravel 419 错误,
问题描述
我的表单数据没有发送任何东西我不知道为什么我试图逐行调试,我发现问题在data: formData
变量中,有人可以帮助我:
我也无法使用 return false 停止重定向
$(function(){
// When Form #xhr is Submited
$('#xhr').submit(function(){
var selectedFile = null;
var data = new FormData();
//if(selectedFile !== null)
data.append('image', selectedFile, selectedFile.name)
$($(form).serializeArray()).each(function(i, field){
data.append(field.name, field.value);
});
$.ajax({
url: $(form).attr('action'),
data: data,
dataType: 'JSON',
cache: false,
contentType: false,
processData: false,
method: 'POST',
success: function(data){
alert(data.success);
}
});
return false;
});
});
解决方案
使用序列化收集数据
var formData = $('form').serializeArray(),
$.ajax({
url: $("#myform").attr('action'),
type: "POST",
data: formData,
contentType: "application/json",
dataType: "json",
success: function(){
alert("yes");
}
});
对于令牌将其添加到您的 html
<meta name="csrf-token" content="{{ csrf_token() }}">
然后在发送ajax请求之前设置这个
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: $("#myform").attr('action'),
type: "POST",
data: formData,
contentType: "application/json",
dataType: "json",
success: function(){
alert("yes");
}
});
例子:
文件:index.blade.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Document</title>
</head>
<body>
<form action="" id="myform">
<input type="text" name="first" id="first">
<input type="text" name="second" id="second">
<input type="text" name="third" id="third">
<button type="button" id="mysubmitbutton">submit</button>
</form>
<script>
$("body").on("click", "#mysubmitbutton", function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf- token"]').attr('content') }
});
$.ajax({
type: "POST",
url: "{{ route('myRouteName') }}",
data: {
'first': $("#first").val(),
'second': $("#second").val(),
'third': $("#third").val()
},
success: function (msg) {
alert('wooow');
}
});
});
</script>
</body>
</html>
在这个简单的示例中,我在标题中设置 csrf 令牌,然后当用户单击按钮时,我收集数据并发送 ajax 请求
推荐阅读
- sql - 无法在 phpMyAdmin 上添加帐户/没有管理用户的权限
- html - 带有 {bslib} 包的 R Shiny 1.6:移动设备上的导航栏样式 - Bootstrap 4 与 Bootstrap 3
- javascript - 如何在 Angular 应用程序的 html 块中查看脚本函数值?
- api - 在颤振中用双引号传递参数值 -
- spring-boot - Jackson - 从嵌套元素开始
- angular - p-columnFilter 不是已知元素
- android - 在 Android 中创建注释常量以用作函数返回类型,类似于 Google Play Billing
- r - 在 R 中,如何根据分类变量的数量删除行?
- python - 这种排序方法的名称是什么?
- javascript - 本地存储 - 来源相同但内容不同