我正在尝试执行ajax调用,但我不断收到
http://127.0.0.1:8000/books/rate/2 404(未找到)
因此它可以很好地获取ID,但显示404错误。
route.php
Route::post('rate/{book_id}','BookController@rate')->name('rate');
main.js
$('#sub').submit(function(e){
var owl = $(this).attr("data");
var route = JSON.parse(owl);
$.ajax({
type:"POST",
url:"rate/" + route.id,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success:function(res){
console.log("owls");
}
});
event.preventDefault();
});
控制器(书本控制器)
public function rate(Request $request, $book_id)
{
$book = Book::find($book_id);
$rating = $book->ratings()->where('user_id', auth()->user()->id)->first();
if(is_null($rating)){
$ratings = new Rating();
$ratings->rating = $request['rating'];
$ratings->user_id = auth()->user()->id;
$book->ratings()->save($ratings);
return json_encode($book);
}
else{
return redirect()->back()->with("status", "You already left a review");
}
}
HTML
<form id="sub" data= "{{ $book }}">
{!! csrf_field() !!}
<div id="rateYo" data-rateyo-rating="{{ $book->userSumRating or 0}}"> ></div>
<input name="rating" value='{{ $book->userSumRating or 0 }}' type="hidden" id="val">
<button type="submit" class="btn btn-primary mt-2">submit</button>
</form>
答案 0 :(得分:1)
我认为您需要对JavaScript进行如下更改
$('#sub').submit(function(e){
var owl = $(this).attr("data");
var route = JSON.parse(owl);
$.ajax({
type:"POST",
url:"http://127.0.0.1:8000/rate/" + route.id,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success:function(res){
console.log("owls");
}
});
event.preventDefault();
});
这是因为在您的URL中,您获得的书是在rate / {rate_id}之前,这就是为什么它显示未找到404页错误的原因!
答案 1 :(得分:1)
您正在使用ajax发布,因此重定向时请使用json响应
public function rate(Request $request, $book_id)
{
$book = Book::find($book_id);
$rating = $book->ratings()->where('user_id', auth()->user()->id)->first();
if(is_null($rating)){
$ratings = new Rating();
$ratings->rating = $request['rating'];
$ratings->user_id = auth()->user()->id;
$book->ratings()->save($ratings);
return json_encode($book);
}
else{
return response()->json(['status' => "You already left a review"]);
}
}
添加尝试此javascript代码
$.ajax({
type:"POST",
url:"http://127.0.0.1:8000/rate/" + route.id,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data:{rating: $('#val').val()},
success:function(res){
console.log("owls");
}
});
答案 2 :(得分:-1)
只需像这样使用它:-
$.ajax({
type:"POST",
url:"{{url('rate/')}}" + route.id,
headers: {
'X-CSRF-TOKEN': {{ csrf_token() }}
},
success:function(res){
console.log("owls");
}
});