使用Jquery和JSON的州和城市列表

<!DOCTYPE html>
<html>
<head>
	<title>使用Jquery和JSON的州和城市列表</title>
	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
<div class="col-sm-6">
	<h2>使用Jquery和JSON的州和城市列表</h2>
	<select class="form-control" id="State">
		<option>选择州</option>
	</select>
	<br>
	<select class="form-control" id="City">
		<option>选择城市</option>
	</select>
	
</div>
</div>

</body>
</html>

<script>
	$(document).ready(function(){
		load_json('State');
		function load_json(id, city_id){
			var html = '';

			$.getJSON('https://xxxx.com/democitys.json', function(data){
				html += '<option>选择'+ id +'</option>';
				console.log(data);
				if(id == 'State' && city_id == null){
					for(var i = 0; i < data.states.length; i++){
						html += '<option value='+ data.states[i].sigla +'>'+ data.states[i].name+'</option>';
					}
				}else{
					for(var i = 0; i < data.states.length; i++){
						if(data.states[i].sigla == city_id){
							for(var j = 0; j < data.states[i].cities.length; j++){
								html += '<option value='+ data.states[i].sigla +'>'+data.states[i].cities[j]+ '</option>';
							}
						}
					}
				}

				$('#'+id).html(html);
			});
			
		}

		$(document).on('change', '#State', function(){
			var city_id = $(this).val();
			console.log(city_id);
			if(city_id != null){
				load_json('City', city_id);
			}
		});

	});
</script>

如图

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/WuLex/article/details/88082271