使用Javascript提交表单并使用ajaxForm处理 [英] Submit a form with Javascript and handle it with ajaxForm

查看:100
本文介绍了使用Javascript提交表单并使用ajaxForm处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在更改系统,以便在提交表单时具有加载进度栏.

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

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系统. /p>

这是我的新代码:

<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>

解决方案

使用此代码,我已经对其进行了检查,它运行良好.如果要测试上传进度,请在Google浏览器的控制台中,选择network→然后在此处选择慢速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> 

I am currently changing my system in order to have a loading progress bar when I now submit my form.

In my old system, I had this form and this script to check if the file exists and is in the right format:

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>

And here is my new system, It works well with ajax but I can't check if the format is correct because as long as I put the onclick:verifyImg(); in my button the form submits without passing by the Ajax system.

Here is my new code:

<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>

These two systems work well separately, but I can't mix them, in order to validate my form with javascript and submit it with Ajax.

I think I'm not understanding well how Ajax works, can you help me?

I am a beginner please be indulgent.

Solution: I tried Chris G answer and changed the function beforeSend by beforeSubmit and now It works perfectly.

Code:

<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>

解决方案

use this code, I've check it, it runs well. If you want to test the upload progress, In google browser's console, select network→then select slow 3G here:

otherwise, you can't see the upload progress increase, you will see 100% in a flash unless you photo has a extremely big size.

user can't select non image file by adding accept attribute to the input box accept="image/*", even if not using this attribute, the javascript will validate the file format by there code, you can add other types here if you need "(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;
    }

This is the full code:

$(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>

这篇关于使用Javascript提交表单并使用ajaxForm处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆