我有一个按钮subscribe,它应该通过ajax向我的控制器提交一个post请求,以便插入到我的表中。
我的视图是这样的:
@extends('layouts.app')
@section('content')
{{$thread->creator->name}} posted:
{{$thread->title}}
@if(auth()->check())
@if($subscription)
Unsubscribe
@else
Subscribe
@endif
@endif
@can('update',$thread)
Edit Thread
@csrf
@method('delete')
Delete Thread
@endcan
{{$thread->body}}
..............
My app.blade:
{{ config('app.name', 'Laravel') }}
body{
padding-bottom:100px;
}
.level{
display: flex;
align-items: center;
}
.flex{
flex: 1;
}
@include('layouts.nav')
@yield('content')
.btn-width{
min-width: 70px;
}
The code calling the button:
$(document).ready(function(){
$('#subscribe').click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('subscription.store')}}",
method:'POST',
data: {
thread_id: "{{$thread->id}}",
},
success:function(response){
$('div.flash-message').html(response);
},
error:function(error){
console.log(error);
}
});
});
});From what I could tell, there is no other element that shares the same id as my button. And, my button is not in a form submit so it should not be called twice. Inspecting dev tools shows no error and in the network tab, two requests are called identically with the same initiator.
So, I am kinda wondering why would this happen. Shouldn't an ajax post request submit the request once only?
I would really like to get to the bottom of this as most of the other similar issues have calling the submit twice while my code is only supposed to call it once. Instead, it makes two insertion to my db.
What else can I do to figure out the root cause of the issue?
发布于 2021-03-02 14:19:59
有没有可能你的javascript以某种方式被加载了两次?这将附加两个相同的侦听器,并在一次单击中发送两次请求。如果将console.log放在事件处理程序中,是否也会看到两倍的效果?
另外,很明显,
为与传递给jQuery对象的选择器匹配的每个元素添加单独的事件侦听器,而
仅添加一个。
..。如果你这样做会发生什么呢?
$(document).ready(function () {
$("#subscribe").on("click", function(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
},
});
$.ajax({
url: "{{route('subscription.store')}}",
method: "POST",
data: {
thread_id: "{{$thread->id}}",
},
success: function (response) {
$("div.flash-message").html(response);
},
error: function (error) {
console.log(error);
},
});
});
});发布于 2021-03-02 14:15:32
您正在调用您的函数两次,第一次是在文档就绪中,第二次是在按钮单击删除程序文档中
发布于 2021-03-02 14:19:37
你有没有试过返回false?如下所示:
$(document).ready(function(){
let subscribeClick = function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('subscription.store')}}",
method:'POST',
data: {
thread_id: "{{$thread->id}}",
},
success:function(response){
$('div.flash-message').html(response);
},
error:function(error){
console.log(error);
}
});
return false;
}
$('#subscribe').click(function(e){
e.preventDefault();
e.stopImmediatePropagation();
subscribeClick();
});
});https://stackoverflow.com/questions/66434045
复制相似问题