我只调用一次ajax,但ajax被多次调用。

huangapple go评论98阅读模式
英文:

I call ajax only once but ajax is called many times

问题

我正在尝试编写一些代码,以便在点击按钮时发出请求。当我点击按钮时,会发出多个请求,我无法弄清楚为什么会发生这种情况。

这是 Blade 文件中按钮的代码:

<div class="form-group">
    @if(!empty($textLesson))

    @php
    $text_id=$textLesson->id;
    $webinar_id=$webinar->id;
    $lessonAudio = App\Models\AudioAttachment::where('text_lesson_id',$text_id)->get();
    @endphp

    <div id="btnDiv">
        <x-panel.attach-audio-component :textid="$text_id" :webinarid="$webinar_id" :textLesson="$textLesson"
            :userLanguages="$userLanguages" />
    </div>
    @if(!empty($lessonAudio) and !$lessonAudio->isEmpty())

    <div id="audioListings">

      </div>
      

这是包含 Ajax 调用的脚本:

<script>
    $(document).ready(function () {

        $('body').on('click', '#addAudio', function (e) {
            const $this = $(this);
            $textid = document.getElementById("addAudio").getAttribute("data-text-id");
            $webinarid = $this.attr('data-webinar-id');
            //alert($textid);
            e.preventDefault();
            let add_audio_modal = '<form id="addAudioFiles" method="post" action="/panel/text-lesson/saveaudio"  enctype= "multipart/form-data">';
            add_audio_modal += '@csrf';
            add_audio_modal += $('#audioFilesModal').html();
            add_audio_modal += '</div>';

            Swal.fire({
                html: add_audio_modal,
                showCancelButton: false,
                showConfirmButton: false,
                customClass: {
                    content: 'p-0 text-left',
                },
                width: '48rem',
            });
        });

        $('body').on('click', '#saveaudios', function (e) {
            e.preventDefault();

            const $this = $(this);
            let form = $('#addAudioFiles');

            let formData = new FormData(form[0]);
            formData.append('webinar_id', $webinarid);
            formData.append('text_id', $textid);
            let action = form.attr('action');

            $this.addClass('loadingbar gray').prop('disabled', true);
            form.find('input').removeClass('is-invalid');
            form.find('textarea').removeClass('is-invalid');

            $.ajax({
                url: action,
                type: 'POST',
                data: formData, // 使用 FormData 对象作为要提交的数据
                processData: false, // 防止 jQuery 处理数据
                contentType: false, // 让浏览器自动设置内容类型
                success: function (result) {
                    if (result && result.code === 200) {

                       // 处理结果

                      

                    },
                    error: function (err) {
                        // 处理错误代码
                    }
                }
            });
        });
    });
</script>

我不知道为什么会发出多个请求。请问是否有人可以提供帮助?

英文:

I am trying to write some code to make a request when I click a button. When I click my button, multiple requests are being made, and I can't figure out why this is happening.

Here is the code of the button in the blade file:

&lt;div class=&quot;form-group&quot;&gt;
@if(!empty($textLesson))
@php
$text_id=$textLesson-&gt;id;
$webinar_id=$webinar-&gt;id;
$lessonAudio = App\Models\AudioAttachment::where(&#39;text_lesson_id&#39;,$text_id)-&gt;get();
@endphp
&lt;div id=&quot;btnDiv&quot;&gt;
&lt;x-panel.attach-audio-component :textid=&quot;$text_id&quot; :webinarid=&quot;$webinar_id&quot; :textLesson=&quot;$textLesson&quot;
:userLanguages=&quot;$userLanguages&quot; /&gt;
&lt;/div&gt;
@if(!empty($lessonAudio) and !$lessonAudio-&gt;isEmpty())
&lt;div id=&quot;audioListings&quot;&gt;
&lt;/div&gt;

Here is the script where ajax is called:

&lt;script&gt;
$(document).ready(function () {
$(&#39;body&#39;).on(&#39;click&#39;, &#39;#addAudio&#39;, function (e) {
const $this = $(this);
$textid = document.getElementById(&quot;addAudio&quot;).getAttribute(&quot;data-text-id&quot;);
$webinarid = $this.attr(&#39;data-webinar-id&#39;);
//alert($textid);
e.preventDefault();
let add_audio_modal = &#39;&lt;form id=&quot;addAudioFiles&quot; method=&quot;post&quot; action=&quot;/panel/text-lesson/saveaudio&quot;  enctype= &quot;multipart/form-data&quot;&gt;&#39;;
add_audio_modal += &#39;@csrf&#39;;
add_audio_modal += $(&#39;#audioFilesModal&#39;).html();
add_audio_modal += &#39;&lt;/div&gt;&#39;;
Swal.fire({
html: add_audio_modal,
showCancelButton: false,
showConfirmButton: false,
customClass: {
content: &#39;p-0 text-left&#39;,
},
width: &#39;48rem&#39;,
});
});
$(&#39;body&#39;).on(&#39;click&#39;, &#39;#saveaudios&#39;, function (e) {
e.preventDefault();
const $this = $(this);
let form = $(&#39;#addAudioFiles&#39;);
let formData = new FormData(form[0]);
formData.append(&#39;webinar_id&#39;, $webinarid);
formData.append(&#39;text_id&#39;, $textid);
let action = form.attr(&#39;action&#39;);
$this.addClass(&#39;loadingbar gray&#39;).prop(&#39;disabled&#39;, true);
form.find(&#39;input&#39;).removeClass(&#39;is-invalid&#39;);
form.find(&#39;textarea&#39;).removeClass(&#39;is-invalid&#39;);
$.ajax({
url: action,
type: &#39;POST&#39;,
data: formData, // use the FormData object as the data to be submitted
processData: false, // prevent jQuery from processing the data
contentType: false, // let the browser set the content type automatically
success: function (result) {
if (result &amp;&amp; result.code === 200) {
// do with result
},
error: function (err) {
// error handling code here
}
});
});
});
&lt;/script&gt;

i dont know why multiple requests are being made. please any one can help

答案1

得分: 0

这是因为您的$('body').on('click', '#saveaudios', function (e) {});注册了多次点击事件。这可能是因为您的脚本加载了多次,事件传播等原因。因此,您需要使用off()事件处理程序来删除先前的事件。因此,您的新代码将如下所示:

$('body').off('click', '#saveaudios').on('click', '#saveaudios', function(e) {
    // 您的ajax逻辑
});
英文:

This is because your $(&#39;body&#39;).on(&#39;click&#39;, &#39;#saveaudios&#39;, function (e) {}); register click events multiple times. This might because of your script is loaded multiple times, event propagation or so on. So, you need to remove the previous event with off() event handler. So, your new code will looks as follows:

$(&#39;body&#39;).off(&#39;click&#39;, &#39;#saveaudios&#39;).on(&#39;click&#39;, &#39;#saveaudios&#39;, function(e) {
// your ajax logic
});

huangapple
  • 本文由 发表于 2023年8月4日 21:25:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76836363.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定