在使用php进行web2.0网站开发时,时常需要用到ajax技术来增加用户体验,当前比较流行的ajax开发框架有prototype,jquery,lightbox等,今天和大家分享如何利用prototype和xml文档进行交互以实现ajax联动下拉菜单的例子。
ajax(asynchronous javascript and xml)使用xhtml和css标准化呈现,使用dom实现动态显示和交互,使用xml和xstl进行数据交换与处理,使用xmlhttprequest对象进行异步数据读取,使用javascript绑定和处理所有数据。
ajax实例(example)说明
主要功能:通过prototype解析xml内容,实现省份和城市之间的二级联动,依此类推,也可以延伸至三级,四级联动
准备工作
下载prototype,并放至相关开发目录,实例中放至在js目录下,当前prototype最新版本为1.6,下载地址为:http://www.prototypejs.org/download
建立省份和城市的相关数据库
新建form表单,并建立两个select框,此处省份select框命名为provincelist,城市select框命名为citylist
代码实例
1
script src=js/prototype.js>script>
注释:引入prototype.js文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
script>
var targetselect;
function getcity(select,target,http)
{
targetselect = target;
var url = http + ?timestamp= + new date().gettime() + &;
var pars = 'province_id='+select.options[select.selectedindex].value;
var myajax =new ajax.request(
url,
{method:'get',parameters:pars,oncomplete:showdestobj}
);
}
function showdestobj(originalrequest)
{
var obj = originalrequest.responsexml;
var properties = obj.getelementsbytagname(property);
var name,value;
targetselect.options.length =properties.length+1;
removeallopt(targetselect);
if(targetselect.options.length >= 0) {
targetselect.options[0] = new option();
targetselect.options[0].value = 0;
targetselect.options[0].text = 请选择;
}
for (var i=0,x=1;iproperties.length;i++,x++)
{
name = properties[i].getelementsbytagname(name)[0].firstchild.nodevalue;
value = properties[i].getelementsbytagname(value)[0].firstchild.nodevalue;
targetselect.options[x] = new option();
targetselect.options[x].value = value;
targetselect.options[x].text = name;
}
}
function removeallopt(sel) {
var arr = sel.options;
for(var i=0; iarr.length; i++) {
sel.remove(i);
}
}
script>
注释:
targetselect:全局变量,存储目标下拉框,也就是citylist
getcity函数用来获取某个省份的所有城市,启动ajax,传递必要的参数。select参数代表源操作select框,即provincelist,target参数代表最终实现自动刷新的select框,即citylist,http参数代表提交至后台处理的php执行文件。
第8行:加入timestamp=” + new date().gettime()的原因是为了防止返回内容无法交互显示,即无法刷新。
第13行:ajax form提交有两种方式:get和post,和一般情况下的表单提交后php进行处理方式的方式是一样的。
特别注意:由于prototype get出去的内容编码是utf8的,如果和数据库或者页面的编码不符,会导致出现中文乱码问题,需要使用相关的编码转换函数进行编码转换,如果你的运行环境支持iconv函数,你也可以使用iconv函数进行编码转换。
showdestobj函数用来处理返回的内容,并通过dom操作实现无刷新页面内容显示。一般情况下返回的内容格式有两种,一种是text格式,一种是xml格式,此处我们返回的内容格式是xml格式的,所以使用了responsexml,如果是text格式,请使用responsetext。
第20行:获取指定标签名对象的集合,getelementsbytagname() 函数用来返回带有指定标签名的对象的集合。后台生成的xml文档循环生成某个省份下城市的相关信息,xml格式为:
1
2
3
4
5
6
7
8
9
10
11
12
>
>
>城市id>
>城市名称>
>
>
>城市id>
>城市名称>
>
>
第23行:removeallopt函数用来每次处理返回内容时清空目标select框
第25~38行:将prototype解析xml后的内容赋予目标select框,以便在页面上显示。
调用方法:
1
select name=provincelist onchange=getcity(this,form1.citylist,'../ajax/province.php')>
总结:
以上就是在使用php进行web2.0网站开发时,如何利用prototype读取xml文档实现二级联动下拉框的ajax实例,是一个比较简单入门的实例,更复杂的应用你可以去prototype的官网查看具体帮助文档,网址为:http://www.prototypejs.org/learn,下次分享如何利用jquery来实现上述功能。
注:php网站开发教程-leapsoul.cn版权所有,转载时请以链接形式注明原始出处及本声明,谢谢。