Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use JSON format to submit a form in HTML5

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

本篇内容主要讲解"HTML5中怎么使用JSON格式提交表单",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"HTML5中怎么使用JSON格式提交表单"吧!

以JSON编码格式提交表单数据是HTML5对WEB发展进化的又一大贡献,以前我们的HTML表单数据是通过key-value方式传输的服务器端,这种形式的传输对数据组织缺乏管理,形式十分原始。而新出现的JSON格式提交表单数据方法,将表单里的所有数据转化的具有一定规范的JSON格式,然后传输的服务器端。服务器端接收到的数据是直接可以使用的合格JSON代码。如何声明以JSON格式提交表单

大家应该对如何用表单上传一个文件的写法很熟悉,它需要在HTML中form标记上添加 enctype="multipart/form-data" 声明,就是告诉浏览器要按上传文件模式发送表单数据。而JSON格式提交表单的声明与此类似,它的写法是: enctype='application/json'。

对老式浏览器的兼容

以JSON格式提交表单是HTML5中一种很新的规范,只有实现了这些规范的现代浏览器才能识别 enctype='application/json'的语义,才能正确的将表单数据打包成JSON格式。而对于一些老式浏览器,以及还未实现这些标准的浏览器,它们无法识别 enctype='application/json'代表什么,于是表单的enctype会自动退化成application/x-www-form-urlencoded缺省编码格式。服务器端代码可以根据enctype的值来判断如何接收数据。

JSON编码格式提交表单的格式范例

例1 基本用法

XML/HTML Code复制内容到剪贴板

Bitable

Kickable

// 生成的Json数据是

{

"name": "Bender"

, "hind": "Bitable"

, "shiny": true

}

例2 当表单存在多个重名的表单域时,按JSON数组编码

XML/HTML Code复制内容到剪贴板

// 生成的Json数据是

{

"bottle-on-wall": [1, 2, 3]

}

例3 表单域名称以数组形成出现的复杂结构

XML/HTML Code复制内容到剪贴板

// 生成的Json数据是

{

"pet": {

"species": "Dahut"

, "name": "Hypatia"

}

, "kids": ["Ashley", "Thelma"]

}

例4 在上面的例子中,缺失的数组序号值将以null替代

XML/HTML Code复制内容到剪贴板

// 生成的Json数据是

{

"hearbeat": ["thunk", null, "thunk"]

}

例5 多重数组嵌套格式,嵌套层数无限制

XML/HTML Code复制内容到剪贴板

// 生成的Json数据是

{

"pet": [

{

"species": "Dahut"

, "name": "Hypatia"

}

, {

"species": "Felis Stultus"

, "name": "Billie"

}

]

}

例6 真的,没有数组维度限制!

XML/HTML Code复制内容到剪贴板

// 生成的Json数据是

{

"wow": {

"such": {

"deep": [

null

, null

, null

, {

"much": {

"power": {

"!": "Amaze"

}

}

}

]

}

}

}

例7 文件上传

XML/HTML Code复制内容到剪贴板

// 假设你上传了2个文件, 生成的Json数据是:

{

"file": [

{

"type": "text/plain",

"name": "dahut.txt",

"body": "REFBQUFBQUFIVVVVVVVVVVVVVCEhIQo="

},

{

"type": "text/plain",

"name": "litany.txt",

"body": "SSBtdXN0IG5vdCBmZWFyLlxuRmVhciBpcyB0aGUgbWluZC1raWxsZXIuCg=="

}

]

}

到此,相信大家对"HTML5中怎么使用JSON格式提交表单"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report