1. 程式人生 > >原生js使用ajax實現省市縣三級聯動

原生js使用ajax實現省市縣三級聯動

chang onchange mes ror charset += ctype type nload

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ajax</title>
    <script>
        window.onload
=function(){ var xhr=new XMLHttpRequest(); xhr.open(get,index.php?type=sheng,true); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ var data=eval(xhr.responseText); var str=<option value="0">--請選擇省--</option>
; for(var i=0; i<data.length; i++){ str+=<option value="+data[i].provinceID+">+data[i].province+</option>; } document.getElementById(province).innerHTML=str; //console.log(data[0].province);
//alert(data); } } xhr.send(); // var province = document.getElementById(province); province.onchange=function(){ var value=this.value; xhr.open(get,index.php?type=shi&provinceID=+value,true); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ var data=eval(xhr.responseText); var str=<option value="0">--請選擇市--</option>; for(var i=0; i<data.length; i++){ str+=<option value="+data[i].cityID+">+data[i].city+</option>; } document.getElementById(city).innerHTML=str; } } xhr.send(); } // var area = document.getElementById(city); city.onchange=function(){ var value=this.value; xhr.open(get,index.php?type=area&cityID=+value,true); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ var data=eval(xhr.responseText); var str=<option value="0">--請選擇縣--</option>; for(var i=0; i<data.length; i++){ str+=<option value="+data[i].areaID+">+data[i].area+</option>; } document.getElementById(area).innerHTML=str; } } xhr.send(); } } </script> </head> <body> <select id="province"> <option value="0">--請選擇省--</option> </select> <select id="city"> <option value="0">--請選擇市--</option> </select> <select id="area"> <option value="0">--請選擇縣--</option> </select> </body> </html>
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "root";
 
// 創建連接
$mysqli = new mysqli($servername, $username, $password);
 
// 檢測連接
if ($mysqli->connect_error) {
    die("連接失敗: " . $mysqli->connect_error);
} 
$mysqli->select_db(‘three‘);
$mysqli->query(‘set names utf8‘);

if($_GET[‘type‘]==‘sheng‘){
    $list=$mysqli->query(‘select * from jing_province‘);

    while($row=$list->fetch_array()){
       $data[]=$row;
    }
    echo json_encode($data);
}elseif($_GET[‘type‘]==‘shi‘){
    $father=$_GET[‘provinceID‘];
    $list=$mysqli->query(‘select * from jing_city where father=‘.$father.‘ ‘);

    while($row=$list->fetch_array()){
       $data[]=$row;
    }
    echo json_encode($data);
}else if($_GET[‘type‘]==‘area‘){
    $father=$_GET[‘cityID‘];
    $list=$mysqli->query(‘select * from jing_area where father=‘.$father.‘ ‘);

    while($row=$list->fetch_array()){
       $data[]=$row;
    }
    echo json_encode($data);
}

原生js使用ajax實現省市縣三級聯動