[英]Refresh a div after successful AJAX operation in Laravel
I want to refresh/update
my div
when a successful ajax
operation occurs. 我想在成功进行
ajax
操作时refresh/update
div
。 But I've no exact idea how to do that. 但是我不知道该怎么做。
Clearly, I can say that my div
should show the inserted
data after the successful insertion operation done by ajax
. 显然,我可以说我的
div
应该在ajax
成功完成插入操作之后显示inserted
数据。 And it obviously should be done without loading page. 而且显然应该在不加载页面的情况下完成。
I'm attaching what I've tried so far. 我附上我到目前为止尝试过的内容。
Route(web.php)
Route::resource('posts', 'PostsController', ['only' => ['store']]);
Cotroller(PostsController)
public function store(Request $request)
{
$this->validate($request, array(
'post' => 'required|min:20',
));
$post=new Post();
$post->userId=Auth::user()->id;
$post->post=$request->post;
$post->save();
return redirect()->route('home');
}
Controller(PagesController)
public function getHome(){
$posts=Post::orderBy('id', 'DESC')->get();
return view('pages.home')->withPosts($posts);
}
JS
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response){
$('.all-posts-body').load(); //No idea how to do this
},
})
Views(home.blade)
<div class="all-posts-body">
@if($posts->isEmpty())
<div class="alert alert-warning">No post yet!</div>
@else
@foreach($posts as $post)
<div class="card">
<div class="card-body">
{!! nl2br($post->post) !!}
</div>
</div>
<br>
@endforeach
@endif
</div>
This .all-posts-body
should be refreshed without reloading page whenever I insert a post by ajax. 每当我通过ajax插入帖子时,应该刷新此
.all-posts-body
而不重新加载页面。
I'm attaching a sample image for better explanation 我附上示例图片,以进行更好的说明
You can send the HTML content that you want from the backend and replace the success
with 您可以从后端发送所需的HTML内容,并将
success
替换为
success: function(response){
$('.all-posts-body').html(response);
},
you can make something like this (i prefer to use id not class) 你可以做这样的事情(我更喜欢使用id而不是class)
$('#all-posts-body').load(location.href+(' #all-posts-body'));
and please add space before your id 请在您的身份证之前添加空格
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.