<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Json Test Demo</title>
<script src="http://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<table border="1" >
<tr>
<td>标题:</td>
<td><input type="text" id="title"></td>
</tr>
<tr>
<td>作者:</td>
<td><input type="text" id="author"></td>
</tr>
<tr>
<td>定价:</td>
<td><input type="text" id="price"></td>
</tr>
<tr>
<td>城市:</td>
<td>
<select id="city">
</select>
</td>
</tr>
<tr>
<td></td>
<td><input type="button" value="显示本地JSON数据" id="btnLocalJSON">
<input type="button" value="将字符串转换为JSON对象" id="btnParseJson">
<input type="button" value="加载城市列表" id="btnLoadCity"></td>
</tr>
</table>
</body>
<script>
$(document).ready(function(){
var book={
'title':'Python入门',
'author':'Eason',
'price':28.9
};
//加载本地的JSON数据
$("#btnLocalJSON").click(function(){
$('#title').val(book.title);
$('#author').val(book.author);
$('#price').val(book.price);
});
//str数据转json
$("#btnParseJson").click(function(){
var str='{"title":"Flask讲义","price":"36.5"}';
var jsonBook= $.parseJSON(str);
console.log("获取json对象book的title:",jsonBook.title);
console.log("获取json对象book的price:",jsonBook.price);
});
//循环
$("#btnLoadCity").click(function(){
var cities=[
{'id':1,'name':'北京'},
{'id':2,'name':'上海'},
{'id':3,'name':'武汉'},
{'id':4,'name':'广州'},
{'id':5,'name':'深圳'}
];
//清空掉列表缓存数据
$("#city").empty();
//遍历载入
$.each(cities,function(i,item){
$("#city").append('<option value="'+item.id+'">'+item.name+'</option>');
});
});
})
</script>
</html>