form 表单提交浏览器的enctype(编码方式)

1. method 为 get 时

  enctype :x-www-form-urlencoded(默认), 把form数据append到对应的url后面;


2. method 为 post 时

   Browser 把form 数据封装到http body 后面;

  a. 没有type=file控件:

    enctype :application/x-www-form-urlencoded (默认) 就可以了;

  b. 有type=file控件:

    enctype:multipart/form-data(显式指定),Browsert会把表单以控件为单位分割,并为每个部分加上Content-Disposition(form-data或者file),Content-Type(默认为text/plain),name(控件name)等信息,并加上分隔符(boundary)

实际业务场景:在提交表单时,表单中存在name控件,同时包含上传的file; 需要将后台返回信息回显过来;

  • 用自带的form报表提交,在from 标签上加 enctype="multipart/form-data";

  可以正常提交 name属性和 file文件,但返回数据前端无法接收到;

  • 用 ajax提交表单数据,用ajax,post等方式处理; 

  要么可以提交单一的file 文件,要么通过 $('form').serialize() 序列化实现提交 name属性的控件;

  • 解决方案:

  借用 jquery.form.js插件(其中另外用了 jquery.validate.js用于数据校验,此插件独立于jquery.form.js),实现代码如下:

var options = {
	rules: {
        ...,
    },
    messages: {
        ...,
    }
};

function showResponse(responseText, statusText) {
  if (statusText == 'success') {
	alert('success');
  }else{
    alert('failed');
  }
}

 //确定
function saveSubmit($from) {
  validator = $from.validate(options);
  $from.submit(function() {
	$(this).ajaxSubmit({
	  type : "post",
	  url : $from.attr('action'),
	  beforeSubmit : function(formData, jqForm, options) {
	    return $from.valid();
	  },
	  success : showResponse
	});
	return false; // 此处必须返回false,阻止常规的form提交
  });
}

  

原文地址:https://www.cnblogs.com/xx0405/p/6565950.html