Website design and developments 1Ajax form Java Script

网站设计与建设 Website design and developments








1)启动一个Ajax过程 form+ Java. Script <FORM METHOD=GET ACTION=”/cgibin/helloworld. pl”> Click here to fire a script: <INPUT TYPE=SUBMIT VALUE=”fire”> </FORM>

<form> <p> City: <input type="text" name="city" id="city" size="25" on. Change="call. Server(); " /> </p> <p> State: < input type="text" name="state" id="state" size="25" on. Change="call. Server(); " /> </p> <p> Zip Code: <input type="text" name="zip. Code" id="city" size="5" /></p> </form>

2)创建一个XMLHttp. Request实例 n 所有现代浏览器均支持 XMLHttp. Request 对象 ¨ IE 7+、Firefox、Chrome、Safari n variable=new XMLHttp. Request(); ¨ IE 5 n 以及 Opera 和 IE 6 使用 Active. XObject variable=new Active. XObject("Microsoft. XMLHTTP");

n IE中安装的 Java. Script 技术版本不同,MSXML 实际上有 两种不同的版本 var xml. Http = false; try {xml. Http = new Active. XObject("Msxml 2. XMLHTTP"); } catch (e) { try { xml. Http = new Active. XObject("Microsoft. XMLHTTP"); } catch (e 2) { xml. Http = false; } } n xml. Http是XMLHttp. Request句柄

function call. Server() { // 从Web表单中获取city 和 state 单元格的值 var city = document. get. Element. By. Id("city"). value; var state = document. get. Element. By. Id("state"). value; if ((city == null) || (city == "")) return; if ((state == null) || (state == "")) return; // 建立URL,escape 函数是一个顶级 Java. Script 函数,可将属性值添加到URL中 var url = "/scripts/get. Zip. Code. php? city=" + escape(city) + "&state=" + escape(state);

// 打开一个与服务器的连接 xml. Http. open("GET", url, true); // 设置结束后服务器运行的函数名 xml. Http. onreadystatechange = update. Page; // 发送这个请求 xml. Http. send(null); }


6)处理服务器响应 function update. Page() { if (xml. Http. ready. State = = 4) { var response = xml. Http. response. Text; document. set. Element. By. Id("zip. Code"). value = response; } }

n response. Text 属性 ¨ 获得字符串形式的响应数据 n response. XML 属性 ¨ 来自服务器的响应是 XML,而且需要作为 XML 对象进行解析 ¨ http: //www. w 3 school. com. cn/ajax_xmlhtt prequest_response. asp

AJAX ASP/PHP 请求实例 http: //www. w 3 school. com. cn/ajax_as p_php. asp n xmlhttp. open("GET", "gethint. php? q="+str, t rue); n //获得来自 URL 的 q 参数 $q=$_GET["q"]; n echo $response; n

AJAX 数据库实例 n AJAX XML 实例 n
- Slides: 19