通过 Vuejs 和 axios 向 Laravel 后端提交 post 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42276661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Submitting a post request through Vuejs and axios to a laravel back-end
提问by Omar Tarek
I need some help in implementing a basic ajax request through vue to my laravel back-end, I have a boolean named completed on a table called courses, and I have a view that fetches all courses assigned to a specific user and allows them to press a button to change the current status of the course, either completed or not, that's it, that's all I wanna do, right now I can do it normally through get and post requests, obviously results in a refresh of the page, I want that to be dynamic with just refreshing the dom, I am so frustrated that I couldn't figure this out on my own because I think It should be easy, turns out I know nothing when it comes to using vuejs.
我需要一些帮助来通过 vue 向我的 Laravel 后端实现基本的 ajax 请求,我在名为 course 的表上有一个名为 Complete 的布尔值,我有一个视图可以获取分配给特定用户的所有课程并允许他们按一个按钮来更改课程的当前状态,无论是否完成,就是这样,这就是我想要做的,现在我可以通过 get 和 post 请求正常进行,显然会导致页面刷新,我想要那个只是刷新 dom 来保持动态,我很沮丧,我无法自己解决这个问题,因为我认为这应该很容易,结果我在使用 vuejs 时一无所知。
Here is the significant part of my CoursesController:
这是我的 CoursesController 的重要部分:
public function toggling($name)
{
$course = Course::where(['name' => $name])->first();
$course->completed = !$course->completed;
$course->save();
// return redirect()->back();
return response()->json(['course' => $course], 202);
}
And here is the significant part of the view that provides the courses to the user, it's a part of a table:
这是向用户提供课程的视图的重要部分,它是表的一部分:
<td>
<form method="POST" @submit.prevent="onSubmit" action="{{ route('course.completed', $course->name) }}" id="form-submit">
{{-- {{ method_field('PUT') }} --}}
{{ csrf_field() }}
@if ($course->completed == true)
<button type="submit" class="btn btn-sm" id="coursetogglingtrue">Done!</button>
@else
<button type="submit" class="btn btn-sm" id="coursetogglingfalse">Not Yet!</button>
@endif
</form>
</td>
For some reason the @submit.prevent method is not working, it worked a couple of times but then It just didn't, and the form kept submitting as usual.
出于某种原因,@submit.prevent 方法不起作用,它工作了几次,但后来它没有工作,并且表单像往常一样继续提交。
These are the scripts inside app.blade.php, I don't know how/where should I compile this, it's just sitting there in the main layout of my project, should I transfer it to public/js/app.js? or compile it using gulp? if you have something in mind please let me know:
这些是 app.blade.php 中的脚本,我不知道如何/在哪里编译它,它只是坐在我项目的主要布局中,我应该将它转移到 public/js/app.js 吗?或使用 gulp 编译它?如果你有什么想法,请告诉我:
<!-- Scripts -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="/js/app.js"></script>
<script>
new Vue({
el: '#app',
data: {
course: {}
},
methods: {
onSubmit() {
// course = $event.target;
axios.post('/MyCourses/{{course.name}}').then(console.log(course));
}
}
});
</script>
I want to have course be equal to whatever value of the request was, so that I can then target the value of the name of the course that was submitted and inject it to the route as I'm trying to do, but I'm not sure how to do that, I tried a few different things, all failed. And here is routes/api.php
我希望 course 等于请求的任何值,以便我可以将提交的课程名称的值作为目标并将其注入到我正在尝试的路线中,但我不知道该怎么做,我尝试了一些不同的事情,都失败了。这里是 routes/api.php
Route::post('/MyCourses/{name}', 'CoursesController@toggling')->name('course.completed');
ofc right now this is not working, the form is submitting, and I'm redirected to a route where I get back the json response, and that's it, I just want to refresh the dom so that the button would have the new id depending on that status of the course, and the course itself to be updated and saved in the background without refreshing the page. I am fairly new to this, I understand that the form should probably be re-written, and I know I've done a lot of mistakes, but I just want it to work, so help would be very appreciated.
ofc 现在这不起作用,表单正在提交,我被重定向到一条路径,在那里我可以返回 json 响应,就是这样,我只想刷新 dom,以便按钮具有新的 id 取决于课程的状态,课程本身将在后台更新和保存,无需刷新页面。我对此很陌生,我知道该表单可能应该重新编写,并且我知道我犯了很多错误,但我只是想让它起作用,因此非常感谢您的帮助。
UPDATE
更新
After a lot of hours of trial and error, I'm done with the ajax part and I'm almost there with the rest I just need to do a few things, this is what I've managed to do so far,
经过大量的反复试验,我已经完成了 ajax 部分,剩下的差不多就完成了,我只需要做一些事情,这是我迄今为止设法做的事情,
In the view:
在视图中:
<form method="POST" @click.prevent="onSubmit" action="{{ route('course.completed', $course->name) }}" id="form-submit">
{{ csrf_field() }}
@if ($course->completed == true)
<button type="button" class="btn btn-sm" id="coursetogglingtrue">Done!</button>
@else
<button type="button" class="btn btn-sm" id="coursetogglingfalse">Not Yet!</button>
@endif
Changing the type of the button from submit to button allowed the .prevent method to actually fire, now the form doesn't submit anymore, the form still needs work in order to output the proper class depending on the status of the course but regardless,
将按钮的类型从提交更改为按钮允许 .prevent 方法实际触发,现在表单不再提交,表单仍然需要工作以根据课程状态输出正确的类,但无论如何,
This is the script that I have now:
这是我现在拥有的脚本:
<script>
new Vue({
el: '#app',
data: {
course: {
name: '',
bool: false
}
},
methods: {
onSubmit: function() {
this.course.bool = !this.course.bool,
axios.post('/MyCourses/{{$course->name}}')
.then(function (response){
// {{$course->completed}} = response.course.completed;
});
}
}
});
</script>
Somehow right now, I'm actually sending the post request to the correct route, but there's a problem which has the highest priority right now, $course is referencing the latest course that was added to the page, and not the course that I chose by pressing on the button, now whichever button I press, the last course gets injected to $course, and then ofc to the route in axois, I don't know how to figure that out yet, but so far that course gets updated, and if I inspected the network tab in chrome, I see the response and that value of the completed column gets updated, I believe that there are still some mistakes in the code, but I'll keep trying, if you can point out some more things please let me know, thanks
现在不知何故,我实际上正在将发布请求发送到正确的路线,但是现在有一个具有最高优先级的问题,$course 引用的是添加到页面的最新课程,而不是我选择的课程通过按下按钮,现在无论我按下哪个按钮,最后一门课程都会注入 $course,然后注入 axois 中的路线,我不知道如何解决这个问题,但到目前为止该课程已更新,如果我检查了 chrome 中的网络选项卡,我会看到响应并且已完成列的值得到更新,我相信代码中仍然存在一些错误,但我会继续尝试,如果你能指出更多事情请告诉我,谢谢
回答by Saurabh
The syntax you are using is wrong in following line:
您使用的语法在以下行中是错误的:
axios.post('/MyCourses/{{course.name}}').then(console.log(course));
It should be :
它应该是 :
axios.post('/MyCourses/' + course.name).then(console.log(course));
回答by Zac Zajdel
An improvement to the answer above would be to use Template Literals introduced in ES6.
对上述答案的改进是使用 ES6 中引入的模板文字。
Instead of:
代替:
axios.post('/MyCourses/' + course.name).then(console.log(course));
You can do:
你可以做:
axios.post(`/MyCourses/${course.name}`).then(console.log(course));
More information on Template Literals functionality and syntax can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
可以在此处找到有关模板文字功能和语法的更多信息:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals