【问题标题】:Submit a form with Javascript and handle it with ajaxForm使用 Javascript 提交表单并使用 ajaxForm 处理
【发布时间】:2019-01-26 14:57:35
【问题描述】:

我目前正在更改我的系统,以便在我现在提交表单时有一个加载进度条。

在我的旧系统中,我有这个表单和这个脚本来检查文件是否存在并且格式是否正确:

Index.php

<form  method="POST" enctype="multipart/form-data" id="myForm" action="upload.php">

    <input type="file" name="imageSent" id="imgFile" class="inputImg" />
    <label for="imgFile" class="labelForImgF">
        <span>Select Img</span>
    </label>

    <button type="button" class="btnSubmit" onclick='verifyImg();'>
        <span>Send</span>
    </button>

</form>

    <script>
function verifyImg() {
    document.getElementById("warning").innerHTML = "";
    var fileName = document.getElementById("imgFile");
    if(fileName.files.item(0) == null) {
        document.getElementById("warning").innerHTML = "You must select an img";
    } else {
        if(!isValidFileType(fileName.files.item(0).name,'image')) {
            document.getElementById("warning").innerHTML = "Bad format";
        } else {
            document.getElementById('myForm').submit();
            document.getElementById("warning").innerHTML = "Sucess";
        }
    }
}

var extensionLists = {}; 
extensionLists.image = ['jpg', 'nef', 'bmp', 'png', 'jpeg', 'svg', 'webp', '3fr', 'arw', 'crw', 'cr2', 'cr3', 'dng', 'kdc', 'mrw', 'nrw', 'orf', 'ptx', 'pef', 'raf', 'R3D', 'rw2', 'srw', 'x3f'];

function isValidFileType(fName, fType) {
return extensionLists[fType].indexOf(fName.toLowerCase().split('.').pop()) > -1;
}
</script>

这是我的新系统,它适用于 ajax,但我无法检查格式是否正确,因为只要我将 onclick:verifyImg(); 放在我的按钮中,表单就会提交而不会通过 Ajax 系统。

这是我的新代码:

<form  method="POST" enctype="multipart/form-data" id="myForm" action="upload.php">

    <input type="file" name="imageSent" id="imgFile" class="inputImg" />
    <label for="imgFile" class="labelForImgF">
        <span>Select Img</span>
    </label>

    <button class="btnSubmit">
        <span>Send</span>
    </button>

</form>
<div id="bararea">
    <div id="bar"></div>
</div>

<div id="percent"></div>
<div id="status"></div>
<script>
$(function() {
$(document).ready(function(){
    var bar = $('#bar')
    var percent = $('#percent');
    var status = $('#status');

    $('form').ajaxForm({
        beforeSend: function() {
            status.empty();
            var percentVal = '0%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            percent.html(percentVal);
            bar.width(percentVal);
        },
        complete: function(xhr) {
            status.html(xhr.responseText);
        }
    });
});
});
</script>

这两个系统分开工作很好,但我不能混合使用,以便使用 javascript 验证我的表单并使用 Ajax 提交。

我觉得我不太了解 Ajax 的工作原理,您能帮帮我吗?

我是初学者,请宽容。

解决方案: 我尝试了 Chris G 的回答并通过 beforeSubmit 更改了 beforeSend 函数,现在它可以完美运行了。

代码:

<form  method="POST" enctype="multipart/form-data" id="myForm" action="upload.php">

    <input type="file" name="imageSent" id="imgFile" class="inputImg" />
    <label for="imgFile" class="labelForImgF">
        <span>Select Img</span>
    </label>

    <button class="btnSubmit">
        <span>Send</span>
    </button>

</form>
<div id="bararea">
    <div id="bar"></div>
</div>

<div id="percent"></div>
<div id="status"></div>
    <script>
function verifyImg() {
    document.getElementById("warning").innerHTML = "";
    var fileName = document.getElementById("imgFile");
    if(fileName.files.item(0) == null) {
        document.getElementById("warning").innerHTML = "You must select an img";
        return false;
    } else {
        if(!isValidFileType(fileName.files.item(0).name,'image')) {
            document.getElementById("warning").innerHTML = "Bad format";
            return false;
        } else {
            return true;
            document.getElementById("warning").innerHTML = "Sucess";
        }
    }
}

var extensionLists = {}; 
extensionLists.image = ['jpg', 'nef', 'bmp', 'png', 'jpeg', 'svg', 'webp', '3fr', 'arw', 'crw', 'cr2', 'cr3', 'dng', 'kdc', 'mrw', 'nrw', 'orf', 'ptx', 'pef', 'raf', 'R3D', 'rw2', 'srw', 'x3f'];

function isValidFileType(fName, fType) {
return extensionLists[fType].indexOf(fName.toLowerCase().split('.').pop()) > -1;
}
</script>
<script>
$(document).ready(function(){
    var bar = $('#bar')
    var percent = $('#percent');
    var status = $('#status');

    $('form').ajaxForm({
        beforeSubmit: function() {
            if (!verifyImg()) return false ;
            status.empty();
            var percentVal = '0%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            percent.html(percentVal);
            bar.width(percentVal);
        },
        complete: function(xhr) {
            status.html(xhr.responseText);
        }
    });
});
</script>

【问题讨论】:

  • 根据文件是否签出,让您的 verifyImg 返回 truefalse。然后在您的beforeSend 函数中执行此操作:if (!verifyImg()) return false; 这应该会阻止表单提交死在其轨道上。然后更改您的代码,以便单击提交按钮提交表单,因此 ajaxForm 接管。
  • 您正在包装两个负载:$(function() { $(document).ready(function(){ 只需要 $(function() {
  • 这里有一些代码:jsfiddle.net/khrismuc/g3jL7k5y
  • @ChrisG 我试过你的代码,但它似乎不起作用,我更新了我的帖子,你发现有什么问题吗?
  • 可能 beforeSend 更改为 beforeSubmit 检查文档。 malsup.com/jquery/form/#options-object

标签: javascript jquery html ajax forms


【解决方案1】:

使用这段代码,我已经检查过了,它运行良好。如果要测试上传进度,在google浏览器的控制台中选择network→然后在这里选择slow 3G:

否则,您看不到上传进度的增加,除非您的照片尺寸非常大,否则您会在一瞬间看到 100%。

用户无法通过在输入框accept="image/*"添加accept属性来选择非图像文件,即使不使用该属性,javascript也会通过代码验证文件格式,您可以在此处添加其他类型如果你需要“(jpeg|png|bmp)”:

    var file = $('input[name="photo"]').get(0).files[0];
    var matchArr = file.type.match(/image\/(jpeg|png|bmp)/);
    if (!matchArr) {
      alert("file type not allow!");
      return false;
    }

这是完整的代码:

$(document).ready(function() {
  $('input[type="button"]').on('click', function() {
    var file = $('input[name="photo"]').get(0).files[0];
    var matchArr = file.type.match(/image\/(jpeg|png|bmp)/);
    if (!matchArr) {
      alert("file type not allow!");
      return false;
    }

    var words = $('input[name="words"]').val();
    var formData = new FormData();
    formData.append('photo', file);
    formData.append('words', words);

    $.ajax({
      type: 'post',
      url: '',
      data: formData,
      //contentType must be false(otherwise it will use default value:application/x-www-form-urlencoded; charset=UTF-8, which is wrong)
      contentType: false,
      //tell jquery don't process data(otherwise it will throw an error:Uncaught TypeError: Illegal invocation)
      processData: false,
      xhr: function() {
        let xhr = new XMLHttpRequest();
        //listening upload progress
        xhr.upload.addEventListener('progress', function(e) {
          if (e.lengthComputable) {
            let progress = e.loaded / e.total;
            progress = Math.round(progress * 10000) / 100 + '%';
            $('.upload-progress').html(progress);
          }
        }, false);
        return xhr;
      },
      success: function(response) {
        console.log(response);
      }
    });
    return false;
  });
});
<html>

<head>
  <title>AjaxFormDataUpload</title>
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
  <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
  <style>
    #upload-form {
      width: 50%;
      margin: 0 auto;
      border: 1px solid blue;
    }
    
    .field {
      padding: 10px;
    }
    
    .submit-btn {
      text-align: center;
      font-size: 20px;
    }
  </style>
</head>

<body>
  <form id="upload-form">
    <div class="field">
      <input type="file" name="photo" accept="image/*">
      <span class="upload-progress"></span>
    </div>
    <div class="field">
      <input type="text" name="words">
    </div>
    <div class="submit-btn">
      <input type="button" value="submit">
    </div>
  </form>
</body>

</html>

【讨论】:

    猜你喜欢
    • 2016-01-06
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 2016-06-23
    • 2011-01-31
    • 1970-01-01
    相关资源
    最近更新 更多