Js表单提交

JavaScript011

Js表单提交,第1张

表单提交是刚开始学js的朋友很迷惑的一个问题,怎么提交,怎么阻止默认提交,怎么提交表单不跳转等等问题,下面是一些示例

原始的表单提交有 button 按钮提交和 <input />类型的。它们又什么区别呢?

(1) 默认表单提交

(2)默认不会提交表单

(3) 如果在 form ,我们使用了 type=''submit 属性,但是不让表单默认提交,有什么办法呢?看下面

(4) 如果在 form ,我们使用了 type=''button 属性,但是还是需要提交表单,这是可以使用ajax来提交,好处是可以自己控制提交,并且页面不会跳转

(5)若是使用默认提交的方法,且提交之前验证表单,方法看下面

(6) 若是使用了 type='button' 属性,但是还是想实现默认提交的方式怎么办? 看下面

(7) 下面的提交会发生什么?

分析 : 点击提交按钮:

(1)当表单验证失败时,不会触发 form.submit() 函数,所以可以触发 <form>的 onsubmit 句柄,又因为该句柄 return false 所以表单不会从该句柄处默认提交,所以 会在控制台打印出 表单的onsubmit事件句柄在form.submit()调用时失效'

(2)当表单验证成功时,会触发 form.submit() 函数提交表单,又因为 form.submit()提交表单的方式与用户单击 Submit 按钮一样,但是表单的 onsubmit 事件句柄不会被调用,所以 控制台不会打印出 表单的onsubmit事件句柄在form.submit()调用时失效

现在表单默认提交的方式基本没人用了,都是ajax异步提交。但是了解一些还是好的。。。

H5edu教育html5开发为您解答:

办法1.同一个页面中建立两个表单 各自提交:

<form action="?" name="form1" id="form1">

<!-- 表单内容 -->

<input type="submit" />

</form>

<form action="?" name="form1" id="form1">

<!-- 表单内容 -->

<input type="submit" />

</form>

办法2:如果非要只有一个表单的话,通过js提交:

<script type="text/javascript" language="javascript">

function submitYouFrom(path){

$('form1').action=path

$('form1').submit()

}

</script>

<form action="?" name="form1" id="form1">

<!-- 表单内容 -->

<input type="button" value="提交1" onclick="submitYouFrom('地址一')"/>

<input type="button" value="提交2" onclick="submitYouFrom('地址二')"/>

</form>

ajax的表单提交只能提交data数据到后台,没法实现file文件的上传还有展示进度功能,这里用到form.js的插件来实现,搭配css样式简单易上手,而且高大上,推荐使用。

需要解释下我的结构, #upload-input-file 的input标签是真实的文件上传按钮,包裹form标签后可以实现上传功能, #upload-input-btn 的button标签是展示给用户的按钮,因为需要样式的美化。上传完成生成的文件名将会显示在 .upload-file-result 里面, .progress 是进度条的位置,先让他隐藏加上 hidden 的class, .progress-bar 是进度条的主体, .progress-bar-status 是进度条的文本提醒。

去掉hidden的class,看到的效果是这样的

[图片上传失败...(image-2c700a-1548557865446)]

将上传事件绑定在file的input里面,绑定方式就随意了。

var progress = $(".progress-bar"), status = $(".progress-bar-status"), percentVal = '0%'//上传步骤 $("#myupload").ajaxSubmit({ url: uploadUrl, type: "POST", dataType: 'json', beforeSend: function () { $(".progress").removeClass("hidden")progress.width(percentVal)status.html(percentVal)}, uploadProgress: function (event, position, total, percentComplete) { percentVal = percentComplete + '%'progress.width(percentVal)status.html(percentVal)console.log(percentVal, position, total)}, success: function (result) { percentVal = '100%'progress.width(percentVal)status.html(percentVal)//获取上传文件信息 uploadFileResult.push(result)// console.log(uploadFileResult)$(".upload-file-result").html(result.name)$("#upload-input-file").val('')}, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(errorThrown)$(".upload-file-result").empty()} })

[图片上传失败...(image-3d6ae0-1548557865446)]

[图片上传失败...(image-9f0adf-1548557865446)]

更多用法可以 参考官网