我试图将表单发送到我的php服务器,但我的Laravel验证表明我的表单是空的。我正在尝试上传相册。我的表单由标题(文本),封面(图像)和照片(图像)组成。我收到422错误(不可处理的实体)。以下是代码
HTML
<form class="lajax" action="{{ action('AlbumController@store') }}" method="POST">
<div class="form-group">
<label>Album Name</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label for="coverFile">Album Cover Image</label>
<input name="cover" type="file" id="coverFile">
<p class="help-block">Example block-level help text here.</p>
</div>
<div class="form-group">
<label for="albumFiles">Album Images</label>
<input type="file" name="photos[]" multiple>
</div>
<button type="submit" class="btn btn-primary">Create Album</button>
</form>
负责ajax的Jquery //将被送入jquerys ajax方法的对象
var ajax_options={
url: url,
method: method,
beforeSend: function(jqXHR,settings){
console.log(jqXHR);
console.log(settings);
if(optns.debug)
console.log('executing beforeSend function');
optns.lajaxBeforeSend($form,formData,jqXHR,settings);
},
success: function(data,textStatus,jqXHR){
if(optns.debug)
console.log('executing success function');
optns.lajaxSuccess($form,formData,data,textStatus,jqXHR)
},
error: function(jqXHR,textStatus,errorThrown){
if(optns.debug)
console.log('error encountered. ajax error function procked');
optns.lajaxError($form,formData,jqXHR,textStatus,errorThrown);
var errors = jqXHR.responseJSON;
console.log(errors);
},
}
//check if files are included in the submitted form if the method is not GET
if($form.find('input:file').length && method!='GET'){
ajax_options.processData=false;
ajax_options.contentType=false;
ajax_options.cache=false;
ajax_options.data=formData;
}
if(optns.debug)
console.log('About to send ajax request');
//sending request here
$.ajax(ajax_options);
laravel php文件
public function store(Request $request)
{
//request input verification rules
$rules=[
'name'=>'required',
'cover'=>'required|image',
'photos'=>'required|array',
'photos.*'=>'image'
];
//perform validation
$this->validate($request,$rules);
//rest of code
}
答案 0 :(得分:1)
请更改按钮类型为按钮,因为要通过ajax发送数据。
如果您想通过ajax发送数据,则可以使用 formdata 。 在formdata中,您可以轻松地将所有图像文件和数据发送到服务器。 请参考:
这是通过ajax将数据发送到服务器的Jquery。
var issueTextFileData = new FormData();
let count = 0;
var imageName = 'issueTextFileData' + ++count;
issueTextFileData.append('singleImage', $('input[name=cover]')[0].files[0]);
issueTextFileData.append(imageName, $('input[name=photos[]]')[0].files[0]);
issueTextFileData.append('albumName', $('input[name=name]')[0].files[0]);
// you can do validation for all files also.
$.ajax({
url: "YOUR URL",
type: "post",
dataType: "json",
data: issueTextFileData,
contentType: false,
processData: false,
beforeSend: function () {
},
success: function (response) {
if (response.status === 200) {
toastr.success(response.message, {timeOut: 3000});
} else {
toastr.error(response.message, {timeOut: 3000});
}
}
});
答案 1 :(得分:0)
尝试添加
enctype="multipart/form-data" files=true
到你的表格标签