简体   繁体   English

如何强制 addEventListener 提交只运行一次

[英]How to force addEventListener submit run only once

I am using a XMLHttpRequest() to upload a file individually in an input.我正在使用XMLHttpRequest()在输入中单独上传文件。 The backend is using Laravel.后端使用 Laravel。

To achieve this, here is part of the code:为了实现这一点,这里是代码的一部分:

The form and input:表格和输入:

<form id="myformid" name="myformid" method="post" action="{{ route('uploadme') }}" enctype="multipart/form-data">
@csrf
   <div class="input-group" id="input_identificacion">
   <div class="custom-file">
      <input type="file" accept=".pdf" class="file-input" id="inputGroupId" name="pdfdoc" aria-describedby="btn_upload_id">
      <label class="file-label" for="inputGroupId" data-browse="Browse" id="inputLabel">Choose a file</label>
   </div>
   <div class="input-group-append" id="div_upload_btn_id">
       <button class="btn btn-outline-info" type="submit" value="submitId" id="btn_upload_id" title="Upload your file now" disabled><i class="fas fa-file-upload"></i>&nbsp;Upload</button>
   </div>
</div>
</form>

And here goes part of the Javascript :这是Javascript 的一部分:

document.getElementById('myformid').addEventListener('submit', function(evt) {
   evt.preventDefault();
   $('#'+btn_upload_id).prop("disabled",true);
   myUpload(this.action,'nameOfInput',e.target.files[0]);
}, {once: true});

Here is part of myUpload() function:这是myUpload()函数的一部分:

function myUpload(url,field,input_file){

   var data = new FormData();
   var request = new XMLHttpRequest();
   request.responseType = "json";

   data.append(field,input_file);
   data.append("_token", "{{ csrf_token() }}");

   {{--Once the request is finished--}}
   request.addEventListener("load",function(e){
      if(request.status === 200){
      }
   }

   request.open("post",url);
   request.send(data);
}

The problem is that sometimes I see the file is uploaded to the system twice.问题是有时我看到文件被上传到系统两次。 How can I prevent that the call to the myUpload() be executed more than once?如何防止myUpload()执行对myUpload()的调用?

You can pass an options object as the third argument with the once property set to true .您可以将选项对象作为第三个参数传递,并将once属性设置为true

document.myformid.addEventListener('submit', function(evt) {
   evt.preventDefault();
   $('#'+btn_upload_id).prop("disabled",true);
   myUpload(this.action,'SomeRequiredvalue',e.target.files[0]);
}, {once: true});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM