我正在尝试使用FormData Api将表单属性发送到服务器,但是我正在从服务器获取422响应代码。否则,相同的代码可以完美地处理另一页上的发布请求。
因此,我删除了代码中的contentType,processData值,并使用Jquery serializeArray()方法,现在可以使用了。我的问题是为什么我的代码的第一种样式不起作用?
//Update Episode Button
var updateEpisodeButton = document.getElementById('updateEpisode');
updateEpisodeButton.onclick = function(e) {
var formData = new FormData(document.getElementById('editEpisodeForm'));
var isFormValid = document.getElementById('editEpisodeForm').checkValidity();
formData.append('description', editor.getData());
console.log(editor.getData());
console.log(formData);
if (isFormValid) {
e.preventDefault();
$.ajax({
url:"{{route('podcast.episode.update',[$podcast->slug,$episode->slug])}}",
dataType:'JSON',
type:'PUT',
contentType: false,
processData: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data:formData,
success:function(result){
swal({
type: 'success',
title: 'Episode Created!',
});
},
error:function(result){
var $data=jQuery.parseJSON(result.responseText);
$errors="";
if (result.status=='422')
{
Object.keys($data.errors).forEach(key => {
$data.errors[key].forEach(errorMessage => {
$errors+=errorMessage+'<br>';
});
});
swal({
type: 'error',
title: 'Oops...',
html:$errors
});
}
},
});
}
}
<form action="" method="POST" id="editEpisodeForm">
<div class="col-md-4"></div>
<div class="col-md-8 float-right">
<div class="form-group">
<label class="font-weight-bold" for="title">Title :</label>
<input type="text" class="form-control" required name="title" value="{{$episode->title}}" placeholder="Type episode title..." id="title">
</div>
<div class="form-group">
<label class="font-weight-bold" for="subtitle">Subtitle :</label>
<input type="text" class="form-control" required name="subtitle" value="{{$episode->subtitle}}" placeholder="Type episode subtitle..." id="subtitle">
<small class="form-text text-muted">This section is optinal*</small>
</div>
<div class="form-group">
<label class="font-weight-bold" for="description">Description :</label>
<textarea id='editor' name="description" rows="10" cols="20">{{$episode->description}}</textarea>
</div>
<div class="form-group">
<label for="explicit">Explicit :</label>
<input type="radio" required name="explicit" value="1"> Yes
<input type="radio" required checked name="explicit" value="0"> No
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-success" id="updateEpisode">Update episode</button>
</div>
</div>
</form>
serializeArray样式的有效载荷