用 PHPRPC 实现 Ajax 级联下拉菜单2
点击次数:20 次 发布日期:2008-11-26 11:42:10 作者:源代码网
|
源代码网推荐 * 设置 select 中的选项,该方法可复用 源代码网推荐 * 源代码网推荐 * so: 要设置选项的 select 对象 源代码网推荐 * d: 选项数据数组 源代码网推荐 * vf: 选项值所对应的数组中的字段名 源代码网推荐 * tf: 选项文本所对应的数组中的字段名 源代码网推荐 */ 源代码网推荐 function set_select(so, d, vf, tf) { 源代码网推荐 for (var i = 0, n = d.length; i < n; i++) { 源代码网推荐 var opt = document.createElement("option"); 源代码网推荐 opt.text = d[i][tf]; 源代码网推荐 opt.value = d[i][vf]; 源代码网推荐 // 有些浏览器不支持 options 属性的 add 方法, 源代码网推荐 // 但支持 DOM 的 appendChild 方法(比如:Konqueror) 源代码网推荐 if (so.options.add) { 源代码网推荐 so.options.add(opt); 源代码网推荐 } 源代码网推荐 else { 源代码网推荐 so.appendChild(opt); 源代码网推荐 } 源代码网推荐 } 源代码网推荐 } 源代码网推荐 源代码网推荐 // 设置省份的下拉菜单 源代码网推荐 function set_province_select(d) { 源代码网推荐 var so = document.getElementById("province"); 源代码网推荐 set_select(so, d, "id", "name"); 源代码网推荐 // 设置首选省份的城市下拉列表 源代码网推荐 change_province(1); 源代码网推荐 } 源代码网推荐 源代码网推荐 // 设置城市的下拉菜单 源代码网推荐 function set_city_select(d, vf, tf) { 源代码网推荐 var so = document.getElementById("city"); 源代码网推荐 // 清空原有选项 源代码网推荐 clear_select(so); 源代码网推荐 // 设置新选项 源代码网推荐 set_select(so, d, vf, tf); 源代码网推荐 } 源代码网推荐 源代码网推荐 // 当省份改变,相应的改变城市列表 源代码网推荐 function change_province(pid) { 源代码网推荐 // 如果已缓存,则直接显示缓存中的列表 源代码网推荐 if (city[pid]) { 源代码网推荐 set_city_select(city[pid], "id", "name"); 源代码网推荐 } 源代码网推荐 else { 源代码网推荐 // 否则,先显示载入中 源代码网推荐 set_city_select([["", "Loading..."]], 0, 1); 源代码网推荐 // 然后调用远程过程载入城市信息 源代码网推荐 // 调用远程过程时,最后一个参数指定的是回调函数 源代码网推荐 rpc.get_city(pid, function (result) { 源代码网推荐 // 把载入的数据放入缓存 源代码网推荐 city[pid] = result; 源代码网推荐 // 更新城市列表 源代码网推荐 set_city_select(result, "id", "name"); 源代码网推荐 }); 源代码网推荐 } 源代码网推荐 } 源代码网推荐 源代码网推荐 // 定义当 rpc 客户端初始化(use_service)完毕后执行的内容 源代码网推荐 rpc.onready = function () { 源代码网推荐 // 调用获取省份内容的远程过程,并设置回调函数为 set_province_select 源代码网推荐 rpc.get_province(set_province_select); 源代码网推荐 } 源代码网推荐 下载: index.html 源代码网推荐 <html> 源代码网推荐 <head> 源代码网推荐 <script type="text/javascript" src="http://www.zzchn.com/edu/20080727/phprpc_client.js"></script> 源代码网推荐 <script type="text/javascript" src="http://www.zzchn.com/edu/20080727/area.js"></script> 源代码网推荐 </head> 源代码网推荐 <body onload="rpc.use_service("rpc.php");"> 源代码网推荐 <select id="province" onchange="change_province(this.value);"></select> 源代码网推荐 <select id="city"></select> 源代码网推荐 </body> 源代码网推荐 </html> 源代码网推荐 上面的 html 中包含的 http://www.zzchn.com/edu/20080727/phprpc_client.js 是压缩版本(因为不需要用到加密,这里是 lite 压缩版)的,这样可以免去包含多个 js 文件的麻烦。 源代码网推荐 源代码网推荐 大家会发现这个程序不但可复用性好(比如 clear_select 和 set_select 两个函数也可以在其它程序中使用),而且使得整个程序的思路清晰,比如那个缓存功能,在这里实现的就非常的简单,而且效果也非常的好。 源代码网推荐 源代码网推荐 演示程序 源代码网推荐 实例下载 源代码网推荐 通过 PHPRPC,你不需要再专注于服务器端和客户端的数据格式交换,不需要再去考虑 XmlHttpRequest 对象的创建和使用,PHPRPC 会自动帮你完成这一切,你只需要关注具体的事务就可以了。用 PHPRPC 来做 Ajax 编程,就是这么简单。 源代码网推荐 做人要厚道,请注明转自酷网动力(www.ASPCOOL.COM)。 源代码网推荐 源代码网供稿. |
