form 表單提交瀏覽器的enctype(編碼方式)

1. method 爲 get 時javascript

  enctype :x-www-form-urlencoded(默認), 把form數據append到對應的url後面;前端


2. method 爲 post 時java

   Browser 把form 數據封裝到http body 後面;jquery

  a. 沒有type=file控件:ajax

    enctype :application/x-www-form-urlencoded (默認) 就能夠了;app

  b. 有type=file控件:post

    enctype:multipart/form-data(顯式指定),Browsert會把表單以控件爲單位分割,併爲每一個部分加上Content-Disposition(form-data或者file),Content-Type(默認爲text/plain),name(控件name)等信息,並加上分隔符(boundary)this

 

實際業務場景:在提交表單時,表單中存在name控件,同時包含上傳的file; 須要將後臺返回信息回顯過來;url

  • 用自帶的form報表提交,在from 標籤上加 enctype="multipart/form-data";

  能夠正常提交 name屬性和 file文件,但返回數據前端沒法接收到;spa

  • 用 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提交
  });
}
相關文章
相關標籤/搜索