`
crazymud
  • 浏览: 57470 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

利用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

?>

 执行效果如下:

1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics