This time I will show you how Ajax realizes the second-level linkage of cities. What are the precautions for Ajax to realize second-level linkage of cities. The following is a practical case, let’s take a look.
1, html
<select id="province"> <option>请选择</option> <option>山东省</option> <option>辽宁省</option> <option>吉林省</option> </select> <select id="city"> <option>请选择</option> </select>
2, javascript
<script> /* * 需要思考哪些事情? * * 在什么时候执行Ajax的异步请求? * * 当用户选择具体的省份信息时 */ // 1. 为id为province元素绑定onchange事件 var provinceEle = document.getElementById("province"); provinceEle.onchange = function(){ // 清空 var city = document.getElementById("city"); var opts = city.getElementsByTagName("option"); for(var z=opts.length-1;z>0;z--){ city.removeChild(opts[z]); } if(provinceEle.value != "请选择"){ // 2. 执行Ajax异步请求 var xhr = getXhr(); xhr.open("post","06.php"); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send("province="+provinceEle.value); xhr.onreadystatechange = function(){ if(xhr.readyState==4&&xhr.status==200){ // 接收服务器端的数据内容 var data = xhr.responseText; // data是字符串,转换为数组 var cities = data.split(","); for(var i=0;i<cities.length;i++){ var option = document.createElement("option"); var textNode = document.createTextNode(cities[i]); option.appendChild(textNode); city.appendChild(option); } } } } }; // 定义获取ajax核心对象的函数XMLHttpRequest对象的函数 function getXhr(){ var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject("Microsoft.XMLHttp"); } return xhr; } </script>
3, 06.php
<?php // 用于处理客户端请求二级联动的数据 // 1. 接收客户端发送的省份信息 $province = $_POST['province']; // 2. 判断当前的省份信息,提供不同的城市信息 switch ($province){ case '山东省': echo '青岛市,济南市,威海市,日照市,德州市'; break; case '辽宁省': echo '沈阳市,大连市,铁岭市,丹东市,锦州市'; break; case '吉林省': echo '长春市,松原市,吉林市,通化市,四平市'; break; } // 服务器端响应的是字符串 ?>
I believe you will read the case in this article You have mastered the method. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Using Blod to make ajax progress bar download
Code caused by multiple asynchronous Ajax requests How to solve nesting
The above is the detailed content of How Ajax realizes urban secondary linkage. For more information, please follow other related articles on the PHP Chinese website!