Javascript+AJAX+JSON+PHP实现列表框联动

由于Ajax的兴起,JSON这种轻量级的数据格式作为客户端与服务器之间的传输格式逐渐地流行起来。

最近项目需要用到在网页不刷新的情况下动态获取数据库内容,并更新到列表框,下午做了个简单的列表框联动,最终效果如下。



下面是完整源代码。

index.html

<!DOCTYPE HTML>
<html>
<head>
<script src="model.js"></script>
<style>
#model{width:150px;}
</style>
<title>列表框联动</title>
</head>

<body>

<select id="brand" οnchange="showModel(this.value)">
<option value="">选择厂商</option>
<option value="shanghai vw">上海大众</option>
<option value="yiqi vw">一汽大众</option>
</select>

<select id="model">
</select>

</body>
</html>

model.js

var xmlHttp;

function showModel (str)
{ 
	xmlHttp = GetXmlHttpObject ();
	if (xmlHttp == null)
	{
		alert ("Browser does not support HTTP Request");
		return;
	}

	var url = "getmodel.php";
	url = url + "?q=" + str;
	url = url + "&sid=" + Math.random ();
	xmlHttp.onreadystatechange = stateChanged;
	xmlHttp.open ("GET", url, true);
	xmlHttp.send (null);
}

function stateChanged ()
{
	clearModelList ();

	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")
	{
		//将服务器返回值转换成JSON对象
		var json = eval ('(' + xmlHttp.responseText + ')'); 

		for (var i = 0; i < json.length; i++) 
		{			
			document.getElementById ("model").options.add (new Option (json[i], json[i]));  
		}
	}
}

//清除列表框  
function clearModelList () 
{
	var modelId = document.getElementById ("model");  

	while (modelId.childNodes.length > 0)
	{
		modelId.removeChild (modelId.childNodes[0]);  
	}
}

//创建 XMLHttpRequest 对象
function GetXmlHttpObject ()
{
	var xmlHttp = null;
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest ();
	}
	catch (e)
	{
		//Internet Explorer
		try
		{
			xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
		}
	}

	return xmlHttp;
}

getmodel.php

<?php
	include '../include/function.php';

	$brand = $_GET["q"];

	if ($conn = db_init ()) 
	{
		$sql = "select model from car_model where brand = '" . $brand . "' order by model";
		$stmt = sqlsrv_query ($conn, $sql);

		if (sqlsrv_has_rows ($stmt))
		{
			$arr = array ();
			while ($row = sqlsrv_fetch_array ($stmt))
			{
				$arr[] = $row['model'];
			}
			sqlsrv_free_stmt ($stmt);

			echo json_encode ($arr);
		}
	}

	if (isset ($conn)) {db_close ($conn); }
?>

数据库car_model表内容

1	shanghai vw	SANTANA
2	shanghai vw	LAVIDA
3	shanghai vw	PASSAT
4	yiqi vw		JETTA
5	yiqi vw		GOLF
6	yiqi vw		SAGITAR
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[car_model]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[car_model]
GO

CREATE TABLE [dbo].[car_model] (
	[id] [int] IDENTITY (1, 1) NOT NULL ,
	[brand] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
	[model] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL 
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[car_model] WITH NOCHECK ADD 
	CONSTRAINT [PK_car_model] PRIMARY KEY  CLUSTERED 
	(
		[id]
	)  ON [PRIMARY] 
GO


========================================

140210 10:45 补充

早上测试时发现如果返回值xmlhttp.responsetext有中文,会出现乱码,经排查是编码问题导致,在修改getmodel.php文件中一句话即可。

$arr[] = $row['model'];

修改为:

$arr[] = iconv ("GB2312", "UTF-8", $row['model']);

iconv函数是PHP提供的字符编码函数,具体参见 iconv函数详解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值