我有一个 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
并通过 的 href 属性获取.like
,其标记如下所示:
<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 请求更新数据库是非常糟糕的做法
因此,我将路由更改为使用 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);
});
另一个更新
正如你们所指出的那样,在此处的文档中,它确实说设置元 CSRF 属性,我什至在控制台中出现错误,说这未定义,但我误解了该错误。
但是,为什么在某些教程中,人们会将 CSRF 令牌添加到数据数组中?
看看这个。你不能{{ csrf_token() }}
在你的 JS 中使用。
在你的 html 中试试这个:
<meta name="csrf-token" content="{{ csrf_token() }}">
这在你的 JS 中:
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句