无刷新页面提交表单
表单可实现无刷新页面提交, 无需页面跳转, 如下, 通过一个隐藏的 iframe 实现, form 表单的 target 设置为 iframe 的 name 名称,
form 提交目标位当前页面 iframe 则不会刷新页面
- <form action="/url.do" method="post" target="targetIfr">
- <input type="text" name="name" />
- </form>
- <iframe name="targetIfr" style="display:none">
- </iframe>
通过 type=submit 提交
一般表单提交通过 type=submit 实现, input type="submit", 浏览器显示为 button 按钮, 通过点击这个按钮提交表单数据跳转到 / url.do
- <form action="/url.do" method="post">
- <input type="text" name="name"/>
- <input type="submit" value="提交">
- </form>
JS 提交 form 表单
JS 事件触发表单提交, 通过 button, 链接等触发事件, JS 调用 submit() 方法提交表单数据, jQuery 通过 submit() 方法
- <form id="form" action="/url.do" method="post">
- <input type="text" name="name"/>
- </form>
- JS: document.getElementById("form").submit();
- jQuery: $("#form").submit();
Ajax 异步提交表单数据
采用 Ajax 异步方式, 通过 JS 获取 form 中所有 input,select 等组件的值, 将这些值组成 JSON 格式, 通过异步的方式与服务器端进行交互,
一般将表单数据传送给服务器端, 服务器端处理数据并返回结果信息等
- <form id="form" method="post">
- <input type="text" name="name" id="name"/>
- </form>
- var params = {"name", $("#name").val()}
- $.Ajax({
- type: "POST",
- url: "/url.do",
- data: params,
- dataType : "JSON",
- success: function(respMsg){
- }
- });
页面无跳转
如果通过 form 表单提交请求服务端去下载文件, 这时当前页面不会发生跳转, 服务端返回 void, 通过 response 去写文件数据,
页面会显示下载文件.
- <form action="/url.do" method="post">
- <input type="text" name="name"/>
- <input type="submit" value="提交">
- </form>
- @RequestMapping(value = "/url")
- public void exportFile(HttpServletRequest req, HttpServletResponse response, String rptId)
- throws Exception {
- OutputStream out = null;
- try {
- String rptName = "file";
- String fileName = new String((rptName + excelAble.getFileSuffix()).getBytes("GBK"),
- "8859_1");
- response.reset();
- response.setContentType("application/octec-stream");
- response.setHeader("Content-disposition", "attachment; filename=" + fileName);
- out = response.getOutputStream();
- excelAble.exportFile(out);
- } catch (Exception e) {
- logger.error(e);
- } finally {
- if (out != null) {
- out.close();
- }
- }
- }
form 表单上传文件
使用 form 表单进行上传文件需要为 form 添加 enctype="multipart/form-data" 属性, 除此之外还需要将表单的提交方法改成 post,
如下 method="post", input type 的类型需要设置为 file
- <form action="/url.do" enctype="multipart/form-data" method="post">
- <input type="file" name="name"/>
- <input type="submit" value="提交">
- </form>
来源: http://www.bubuko.com/infodetail-2791093.html