以JSON编码格式提交表单数据是HTML5对WEB发展进化的又一大贡献,之前咱们的HTML表单数据是经过key-value方式传输的服务器端,这种形式的传输对数据组织缺少管理,形式十分原始。而新出现的JSON格式提交表单数据方法,将表单里的全部数据转化的具备必定规范的JSON格式,而后传输的服务器端。服务器端接收到的数据是直接能够使用的合格JSON代码。php
你们应该对如何用表单上传一个文件的写法很熟悉,它须要在HTML中form标记上添加 enctype="multipart/form-data" 声明,就是告诉浏览器要按上传文件模式发送表单数据。而JSON格式提交表单的声明与此相似,它的写法是: enctype='application/json'。html
以JSON格式提交表单是HTML5中一种很新的规范,只有实现了这些规范的现代浏览器才能识别 enctype='application/json'的语义,才能正确的将表单数据打包成JSON格式。而对于一些老式浏览器,以及还未实现这些标准的浏览器,它们没法识别 enctype='application/json'表明什么,因而表单的enctype会自动退化成application/x-www-form-urlencoded缺省编码格式。服务器端代码能够根据enctype的值来判断如何接收数据。web
<form enctype='application/json'> <input name='name' value='Bender'> <select name='hind'> <option selected>Bitable</option> <option>Kickable</option> </select> <input type='checkbox' name='shiny' checked> </form> // 生成的Json数据是 { "name": "Bender" , "hind": "Bitable" , "shiny": true }
<form enctype='application/json'> <input type='number' name='bottle-on-wall' value='1'> <input type='number' name='bottle-on-wall' value='2'> <input type='number' name='bottle-on-wall' value='3'> </form> // 生成的Json数据是 { "bottle-on-wall": [1, 2, 3] }
<form enctype='application/json'> <input name='pet[species]' value='Dahut'> <input name='pet[name]' value='Hypatia'> <input name='kids[1]' value='Thelma'> <input name='kids[0]' value='Ashley'> </form> // 生成的Json数据是 { "pet": { "species": "Dahut" , "name": "Hypatia" } , "kids": ["Ashley", "Thelma"] }
<form enctype='application/json'> <input name='hearbeat[0]' value='thunk'> <input name='hearbeat[2]' value='thunk'> </form> // 生成的Json数据是 { "hearbeat": ["thunk", null, "thunk"] }
<form enctype='application/json'> <input name='pet[0][species]' value='Dahut'> <input name='pet[0][name]' value='Hypatia'> <input name='pet[1][species]' value='Felis Stultus'> <input name='pet[1][name]' value='Billie'> </form> // 生成的Json数据是 { "pet": [ { "species": "Dahut" , "name": "Hypatia" } , { "species": "Felis Stultus" , "name": "Billie" } ] }
<form enctype='application/json'>
<input name='wow[such][deep][3][much][power][!]' value='Amaze'>
</form>
// 生成的Json数据是
{
"wow": {
"such": {
"deep": [
null
, null
, null
, {
"much": {
"power": {
"!": "Amaze"
}
}
}
]
}
}
}
<form enctype='application/json'> <input type='file' name='file' multiple> </form> // 假设你上传了2个文件, 生成的Json数据是: { "file": [ { "type": "text/plain", "name": "dahut.txt", "body": "REFBQUFBQUFIVVVVVVVVVVVVVCEhIQo=" }, { "type": "text/plain", "name": "litany.txt", "body": "SSBtdXN0IG5vdCBmZWFyLlxuRmVhciBpcyB0aGUgbWluZC1raWxsZXIuCg==" } ] }