Jquery 使用AJAX将HTML输入标记中的多个图像与表单外部的其他数据一起发送到Laravel控制器

Jquery 使用AJAX将HTML输入标记中的多个图像与表单外部的其他数据一起发送到Laravel控制器,jquery,json,ajax,laravel,Jquery,Json,Ajax,Laravel,})) 我想做的是编辑一篇文章。所发生的是,一个编辑模式打开,以前的数据和照片显示给用户。如果用户单击“删除”按钮,则该帖子的所有照片都将被删除。他可以编辑将在数据库中更新的文本。现在,我正在使用ajax发送执行此操作所需的数据。现在我想将新照片插入到该帖子中。我的html中有一个多输入标记 $('#modal-save').on('click', function(event){ $.ajax({ method: 'POST', url: urlEdit, data:

}))

我想做的是编辑一篇文章。所发生的是,一个编辑模式打开,以前的数据和照片显示给用户。如果用户单击“删除”按钮,则该帖子的所有照片都将被删除。他可以编辑将在数据库中更新的文本。现在,我正在使用ajax发送执行此操作所需的数据。现在我想将新照片插入到该帖子中。我的html中有一个多输入标记

$('#modal-save').on('click', function(event){
$.ajax({
    method: 'POST',
    url: urlEdit,
    data: {
        body: $('#post-body').val(),
        deletePhoto: deletePhoto,
        postId: postId,
         _token: token 
    }
})
.done(function(msg){
    $(postBodyElement).text(msg['new_body']);
    location.reload();
    $('#edit-modal').modal('hide');
});

您将需要以下内容:

HTML:

控制器:

let data = new FormData();
let input = document.getElementById("images-input");

data.append('body', $('#post-body').val());
data.append('deletePhoto', deletePhoto);
data.append('postId', postId);
data.append('_token', token); 
data.append('images', input.files.map(function (image) {
    return image.file;
});

$.ajax({
    method: 'POST',
    url: urlEdit,
    headers: {
        'content-type': 'multipart/form-data',
    },
    data: data,
})

现在您有了一个UploadedFile对象数组,您可以随心所欲。

两个关键部分是:标题:{“内容类型”:“多部分/表单数据”},以及document.getElementById(“创建游戏文件”).files[0]。此外,您还需要使用FormData进行发布。
 public function postEditPost(Request $request)
{
    $this->validate($request, [
        'body' => 'required'
    ]);
    $post = Post::find($request['postId']);
    if (Auth::user() != $post->user){
        return redirect()->back();
    }
    $photos = Photos::where('post_id', $request['postId'])->get();
    $deletePhoto =  $request['deletePhoto'];
    if($deletePhoto == 0){
        foreach($photos as $photo){
            $photo->delete();
        }
    }
  
    $post->body = $request['body'];
    $post->update();
    return response()->json(['new_body' => $post->body],200);
}
<input id="images-input" class="post-input" type="file" multiple accept='image/*' />
let data = new FormData();
let input = document.getElementById("images-input");

data.append('body', $('#post-body').val());
data.append('deletePhoto', deletePhoto);
data.append('postId', postId);
data.append('_token', token); 
data.append('images', input.files.map(function (image) {
    return image.file;
});

$.ajax({
    method: 'POST',
    url: urlEdit,
    headers: {
        'content-type': 'multipart/form-data',
    },
    data: data,
})
public function postEditPost(Request $request)
{
    $this->validate($request, [
        ...
        'images' => ['nullable', 'array'], // Unless they are mandatory,
        'images.*' => ['image'],
    ]);

    $images = [];
    
    foreach ($request->input('images') as $key => $image) {
        $images[] = $request->file("images.$key");
    }
    ...
}