JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。它基于 ECMAScript (欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
JSON语法:
{ "username":"laochen", "password":"123456", "fruits":["苹果","雪梨","香蕉"] } |
前端解析JSON格式字符串
JSON.parse(str) //将JSON格式的字符串解析成JSON对象
JSON.stringify(obj) //将对象转化为JSON格式的字符串
简单用户密码json代码案例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/ajax.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<!--<form action="http://localhost/day12-01ajaxForm/ResForm" method="post">
<input type="text" name="username" id="username" value="" />
<input type="text" name="password" id="password" value="" />
<input type="submit" value="登录"/>
</form>-->
<input type="text" name="username" id="username" value="" />
<input type="text" name="password" id="password" value="" />
<button>登录</button>
<h3>用户信息</h3>
<h4>用户名:<span class="user"></span></h4>
<h4>用户密码:<span class="passwd"></span></h4>
<h4>服务器响应状态:<span class="status"></span></h4>
<script type="text/javascript">
var usernameDom = document.querySelector('#username');
var passwordDom = document.querySelector('#password');
var btn = document.querySelector('button')
btn.onclick = function(){
var username = usernameDom.value;
var password = passwordDom.value;
var options = {
url:"http://localhost/day12-03AjaxJson/ResForm",
data: {
"username":username,
"password":password
},
fn:function(xhr){
console.log(xhr.response)
//解析JSON格式的字符串
var jsonStr = xhr.response;
var jsonObj = JSON.parse(jsonStr);
console.log(jsonObj);
var userDom = document.querySelector(".user");
var passwdDom = document.querySelector(".passwd");
var statusDom = document.querySelector(".status");
userDom.innerHTML = jsonObj.username;
passwdDom.innerHTML = jsonObj.password;
statusDom.innerHTML = jsonObj.status;
}
}
post(options)
}
var student = {
username:"小李",
age:20,
like:"唱跳rap篮球"
}
var jsonStr = JSON.stringify(student)
console.log(jsonStr)
</script>
</body>
</html>
<!--html/xml
<username>laochen</username>
<password>123456</password>
{
"username":"laochen",
"password":"123456",
"fruits":["苹果","雪梨","香蕉"]
}-->