我有一个AJAX请求,这是一个GET请求。
/**
* AJAX Like function
*/
$(".like").click(function (e) {
e.preventDefault(); // you dont want your anchor to redirect so prevent it
$.ajax({
type: "GET",
// blade.php already loaded with contents we need, so we just need to
// select the anchor attribute href with js.
url: $('.like').attr('href'),
success: function () {
if ($('.like').hasClass('liked')) {
$(".like").removeClass("liked");
$(".like").addClass("unliked");
$('.like').attr('title', 'Like this');
} else {
$(".like").removeClass("unliked");
$(".like").addClass("liked");
$('.like').attr('title', 'Unlike this');
}
}
});
});
网址为:http://127.0.0.1:8000/like/article/145
并通过.like
的href属性获取,其标记如下:
<div class="interaction-item">
@if($article->isLiked)
<a href="{{ action('LikeController@likeArticle', $article->id) }}" class="interactor like liked" role="button" tabindex="0" title="Unlike this">
@else
<a href="{{ action('LikeController@likeArticle', $article->id) }}" class="interactor like unliked" role="button" tabindex="0" title="Like this">
@endif
<div class="icon-block">
<i class="fas fa-heart"></i>
</div>
</a>
</div>
LikeController 如下所示:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Like;
use App\Article;
use App\Event;
use Illuminate\Support\Facades\Auth;
class LikeController extends Controller
{
/**
* Display all liked content for this user
*/
public function index()
{
$user = Auth::user();
$articles = $user->likedArticles()->get();
$articleCount = count($articles);
$events = $user->likedEvents()->get();
$eventCount = count($events);
return view('pages.likes.index', compact('articles', 'articleCount', 'events', 'eventCount'));
}
/**
* Handle the liking of an Article
*
* @param int $id
* @return void
*/
public function likeArticle($id)
{
// here you can check if product exists or is valid or whatever
$this->handleLike(Article::class, $id);
return redirect()->back();
}
/**
* Handle the liking of an Event
*
* @param int $id
* @return void
*/
public function likeEvent($id)
{
// here you can check if product exists or is valid or whatever
$this->handleLike(Event::class, $id);
return redirect()->back();
}
/**
* Handle a Like
* First we check the existing Likes as well as the currently soft deleted likes.
* If this Like doesn't exist, we create it using the given fields
*
*
* @param [type] $type
* @param [type] $id
* @return void
*/
public function handleLike($type, $id)
{
$existingLike = Like::withTrashed()
->whereLikeableType($type)
->whereLikeableId($id)
->whereUserUsername(Auth::user()->username)
->first();
if (is_null($existingLike)) {
// This user hasn't liked this thing so we add it
Like::create([
'user_username' => Auth::user()->username,
'likeable_id' => $id,
'likeable_type' => $type,
]);
} else {
// As existingLike was not null we need to effectively un-like this thing
if (is_null($existingLike->deleted_at)) {
$existingLike->delete();
} else {
$existingLike->restore();
}
}
}
}
我认为通过GET请求更新数据库是非常糟糕的做法
所以,我改变了Route以使用POST并将AJAX调用更新为:
/**
* AJAX Like function
*/
$(".like").click(function (e) {
e.preventDefault(); // you dont want your anchor to redirect so prevent it
$.ajax({
type: "POST",
// blade.php already loaded with contents we need, so we just need to
// select the anchor attribute href with js.
url: $('.like').attr('href'),
data: {
_token: '{{ csrf_token() }}'
},
success: function () {
if ($('.like').hasClass('liked')) {
$(".like").removeClass("liked");
$(".like").addClass("unliked");
$('.like').attr('title', 'Like this');
} else {
$(".like").removeClass("unliked");
$(".like").addClass("liked");
$('.like').attr('title', 'Unlike this');
}
}
});
});
如您所见,我已更改方法并添加到CSRF令牌中,但是,我收到错误:
POST http://127.0.0.1:8000/like/article/145 419 (unknown status)
send @ app.js:14492
ajax @ app.js:14098
(anonymous) @ app.js:27608
dispatch @ app.js:10075
elemData.handle @ app.js:9883
app.js:14492 XHR failed loading: POST "http://127.0.0.1:8000/watch/article/145".
调试正在进行的操作的最佳方法是什么?
更新
添加:<meta name="csrf-token" content="{{ csrf_token() }}">
是否会干扰我在表单中正常使用“@csrf”?
另外,我在请求中添加了一个失败的回调
}).fail(function (jqXHR, textStatus, error) {
// Handle error here
console.log(jqXHR.responseText);
});
另一次更新
正如你所有人都指出的那样,在文档here中,它确实说,设置元CSRF属性,我甚至在我的控制台中有一个错误,说这个没有定义,但我误解了错误。
为什么在某些教程中,人们会将CSRF令牌添加到数据数组中吗?
答案 0 :(得分:4)
看看this。您无法在JS中使用{{ csrf_token() }}
。
在你的html中试试这个:
<meta name="csrf-token" content="{{ csrf_token() }}">
这在你的JS中:
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
答案 1 :(得分:1)
如果您在单个文件中有多个ajax调用,那么您可以通过此方法执行此操作。以下代码适用于您的所有AJAX请求。
在你的html中试试这个:
<meta name="csrf-token" content="{{ csrf_token() }}">
这在你的JS中:
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});