天天看點

利用JQuery制作簡單二級關聯

剛開始學jquery,試着用jquery做了一個小例子:省市的二級關聯。

在資料庫test中建表province和city。province有字段id和name。city表中字段是id,city_name和province_id。

view部分代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$(document).ready(function() {
  //get provinces
  $.get("getcontent.php", {category:'province'},
    function(data) {
      $('#province').html(data);
  });

  //get citys
  $.get("getcontent.php", {category:'city'},
    function(data) {
	  $('#city').html(data);
	});

	//province onchange
	$('#province').change(function() {
	  var province = $(this).val();
	  $.get("getcontent.php", {category:'city', province:province}, function(data) {
	    $('#city').html(data);
	  });
	});

});

</script>

<title>二級關聯示例</title>
</head>
<body>

<form>
  位址:
  <select name="province" id="province">
    <option>選擇省份</option>
  </select>
  <select name="city" id="city">
    <option value='0'>選擇城市</option>
  </select>
</form>
</body>
</html>
           

 php部分:

<?php
  define(HOST, 'localhost');
  define(USER, 'root');
  define(PW, '');
  define(DB, 'test');
  
  $connect = mysql_connect(HOST, USER, PW)
  or die('Could not connect to mysql server');

  mysql_select_db(DB,$connect)
  or die('Could not select database.');
  //設定查詢編碼,不設查詢時易出現亂碼
  mysql_query('set names utf8;');

  switch($_REQUEST['category']) {
	//顯示資料庫中所有省份
    case 'province':
		$str = "<option value='0'>請選擇省份</option>";
	    $sql = "select * from province";
		$result = mysql_query($sql) or die (mysql_error());
		
		if (mysql_num_rows($result) > 0) {
		  while ($row = mysql_fetch_array($result)) {
		    //print_r($row);
			$str .= "<option value='".$row['id']."'>".$row['name']."</option>";
		  }
		}
		echo $str;
		mysql_free_result($result);
		break;

    //顯示城市
    case 'city':
		$str = "<option value='0'>請選擇城市</option>";
	    if($_REQUEST["province"] != "") {
           //根據省份得到城市
	    $sql = "select * from city where province_id=".$_REQUEST['province'];
		$result = mysql_query($sql) or die (mysql_error());

		if (mysql_num_rows($result) > 0) {
		  while ($row = mysql_fetch_array($result)) {
		    $str .= "<option value='".$row['id']."'>".$row['city_name']."</option>";
		  }
		}
		mysql_free_result($result);
		}//end of if
		echo $str;
		break;
		
  }//end of switch

?>
           

 執行效果如下:

利用JQuery制作簡單二級關聯
利用JQuery制作簡單二級關聯