运行效果:
说明:
Ajax获取Json数据列表,再循环查询对应的数据,如果未找到,给出提示。
示例源码:
JS代码:
$('#btnQuery').on('click', function () { var name = $('input:text').val(); $.ajax({ type: 'GET', url: 'bjyb.json', // data: {name:name}, dataType: 'json', success: function (data) { var flag = false; //是否找到标识 //遍历Json数据 $.each(data, function (key, value) { if (key == name) { $('#result').html(value); flag = true; } }) if(flag == false) { //未找到给出提示 $('#result').html('<span style="color: orangered">暂未收录!</span>') } } }); }); </script>
HTML全文
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax+Json查询</title> <link rel="stylesheet" href="http://demo.h-ui.net/H-ui.admin/3.1/static/h-ui/css/H-ui.min.css"> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> </head> <body> <div class="containBox"> <div class="containBox-bg"></div> <div class="wap-container"> <div class="container ui-sortable"> <div class="panel panel-default mt-20" style="width:500px;margin:0 auto"> <div class="panel-header selected">北京市邮编查询</div> <div class="album"> <div class="select"> <div class="row cl"> <label class="form-label col-sm-2 col-md-3">输入区、县名称:</label> <div class="formControls col-sm-5 col-md-5"> <input type="text" name="url" class="input-text"> </div> </div> <div class="row cl"> <div class="formControls col-md-5"> <button id="btnQuery" class="btn btn-primary size-L">查询</button> </div> </div> </div> </div> <div class="panel-body" style="display: block;"> <div id='result' class="result"></div> </div> </div> </div> </div> </div> <script> $('#btnQuery').on('click', function () { var name = $('input:text').val(); $.ajax({ type: 'GET', url: 'bjyb.json', // data: {name:name}, dataType: 'json', success: function (data) { var flag = false;//是否找到标识 //遍历Json数据 $.each(data, function (key, value) { if (key == name) { $('#result').html(value); flag = true; } }) if(flag == false) { //未找到给出提示 $('#result').html('<span style="color: orangered">暂未收录!</span>') } } }); }); </script> </body> </html> </body> </html>
JSON数据:
{ "东城区": "100001", "西城区": "100009", "崇文区": "100022", "宣武区": "100050", "朝阳区": "100006", "海淀区": "100036" }