使用 js 和 triger 事件“提交”提交表单

大家好 这是我的代码:


HTML:


<html>

    <body>

        <form enctype="multipart/form-data" method="post" name="image">

            <input onchange="test();" type="file" accept="image/*" capture="camera" name="file" id="camera">

            <input id="go" type="submit" value="Stash the file!" style="display: none;" />

        </form>

        <div id="output"></div>

    </body>

    <script src="./script.js"></script>

</html>

JS:


var form = document.forms.namedItem("image");

form.addEventListener('submit', function(ev) {


   var

       oOutput = document.getElementById("output"),

       oData = new FormData(document.forms.namedItem("image"));


   oData.append("CustomField", "This is some extra data");


   var oReq = new XMLHttpRequest();

   oReq.open("POST", "./upload.php", true);

   oReq.onload = function(oEvent) {

       if (oReq.status == 200) {

           oOutput.innerHTML = "Uploaded!";

       } else {

           oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>";

       }

   };


   oReq.send(oData);

   ev.preventDefault();

}, false);


function test() {

   document.getElementById("go").click()

}

我的问题是它功能齐全,但有点……脏。


我尝试用 JS 提交表单document.forms.namedItem("image").submit();,但 EventListener 没有捕获它。


我不想只是为了这个而将 JQuery 添加到我的项目中(对于那些使用 JQuery 有答案的人)。


解决方案当然就在我眼前,但我找不到其他方法来做到这一点。


预先感谢大家。


婷婷同学_
浏览 97回答 1
1回答

慕标5832272

我认为你可以这样简化:function pleaseUpload() {&nbsp; &nbsp;console.log('upload fonction ...');}<html>&nbsp; &nbsp; <body>&nbsp; &nbsp; &nbsp; &nbsp; <form enctype="multipart/form-data" method="post" name="image">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input onchange="pleaseUpload();" type="file" accept="image/*" capture="camera" name="file" id="camera">&nbsp; &nbsp; &nbsp; &nbsp; </form>&nbsp; &nbsp; &nbsp; &nbsp; <div id="output"></div>&nbsp; &nbsp; </body>&nbsp; &nbsp; <script src="./temp.js"></script></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript