json客户端简易实现

1.点击显示内容按钮将book中的标题,作者,定价显示到表格中对应字段上
这里写图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
    <title>json</title>
</head>
<body>
<table>
        <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><input type="button" value="显示内容" id="btn"></td>
        </tr>
</table>
</body>
</html>
<script>
    $(document).ready( function () {
        ##定义book对象
        var book = {
            'title':'python',
            'author':'tom',
            'price':'200',
        };
        ##点击按钮后,将book中键对应的值显示至表格中
        $('#btn').click( function () {
            $('#title').val(book.title);
            $('#author').val(book.author);
            $('#price').val(book.price);
        });
</script>

2.点击按钮将字符串转换为json对象并显示至文本框中
这里写图片描述

<script>
    $('#btnparse').click( function () {
        var book='{"title":"flask","author":"nancy","price":"300"}'; ##声明字符串类型
        var jsonbook=$.parseJSON(book); ##将字符串转换为json

            $('#title').val(book.title);
            $('#author').val(book.author);
            $('#price').val(book.price);
    });
</script>

3.点击按钮将城市载入至下拉框中
这里写图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
    <title>json</title>
</head>
<body>
<table>


       <tr>
            <td>城市:</td>
            <td><select name="city" id="city">

            </select></td>
        </tr>

</table>

<button id="loadcity">载入城市</button>

</body>
</html>
<script>
    $('#loadcity').click( function () {
        var cities =[
        {'id':1,'name':'北京'},
        {'id':2,'name':'上海'},
        {'id':3,'name':'广州'},
        ];
        $('#city').empty();   ##清空city下拉框中的内容
        $.each( cities,function (i,city) {  ##i为索引,city为每个遍历出的对象
            $('#city').append('<option value="'+city.id+'">'+city.name+'</option>'); ##每遍历出一个对象添加内容
        });  
    });

猜你喜欢

转载自blog.csdn.net/qq1105273619/article/details/79990666