javascript - 使用 jQuery 提交简单表单 - 为什么这在 IE9 中不起作用?

标签 javascript jquery html forms

这是我的代码:

<html>
<head>
<style type="text/css">
#myform {display:none;}
</style>
</head>

<body>
<button type="button" id="uploadbutton">Upload Images</button>
<form name="myform" id="myform" method="POST" action="http://www.########.com/post.php" enctype="multipart/form-data">
  <input type="file" name="imagefile" id="imagefile" accept="image/*" onchange="FileSelected();" />
</form>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$('#uploadbutton').click(function() {
    $('#imagefile').trigger('click');
});

function FileSelected() {
 document.getElementById("myform").submit();
}
</script>
</body>
</html>

我试图让它在 IE9 和更旧的浏览器中工作,但是 jQuery submit() 函数没有触发。最终,我正在构建一个脚本,该脚本可以在不刷新页面的情况下提交图像并且隐藏表单。一个复杂的 FileSelected() 函数在现代浏览器上通过 AJAX 提交文件图像,尽管我需要帮助获得替代方案以在不支持此 AJAX/文件提交的旧浏览器上工作。

让我们从简单的开始:为什么上面的这个小脚本不能在 IE9 上运行?

最佳答案

发生这种情况是因为您没有提交表单。

代替:

$('#imagefile').trigger('click');

你需要使用:

$('#myform').submit();

我的片段:

$(function () {
  $('#imagefile').on('change', function (e) {
    if (this.value != '') {
      alert('loaded');

      // uncomment for testing
      //$('#myform').submit();
    }
  });

  $('#uploadbutton').click(function () {
    $('#imagefile').trigger('click');
  });
});
#myform {
   display:none;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<button type="button" id="uploadbutton">Upload Images</button>
<form name="myform" id="myform" method="POST" action="http://www.########.com/post.php" enctype="multipart/form-data">
    <input type="file" name="imagefile" id="imagefile" accept="image/*"/>
</form>

关于javascript - 使用 jQuery 提交简单表单 - 为什么这在 IE9 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38211390/

相关文章:

javascript - 从父 Controller 在 Angular Modal 中显示动态内容

javascript - 使用具有 <img> 标签的 Javascript 动态添加 HTML。如何判断图像何时加载

javascript - 检查 html 是否有一个类,如果是真的,则打印一个没有 jquery 的结果

javascript - 使用通过元素事件处理程序传递的参数(this)

c# - 在 WPF 中放入像 Html Float Resource 这样的图片

javascript - 准备和使用带有区域和年份子集的 moment-timezone.js 的步骤是什么

javascript - jquery 中的 on() 函数不起作用

php - JQuery 删除和添加类

javascript - 脚本有效但有错误 : Uncaught TypeError: Cannot read property 'classList' of null at HTMLAnchorElement

javascript - 使用javascript将自定义json对象复制到剪贴板