世界上有些事就是为了让你干了以后后悔而设,所以你不管干了什么事,都不要后悔。

《AJAX高级程序设计》读书笔记(二)

基于图象的AJAX
在AJAX通信中使用图像背后的技术与图像载入技术类似,需要创建一个<img />元素,然后为其src特性赋值,或者使用Image对象。

getcusdata.php
1 <?php
2 header("Content-Type:image/gif");
3 $cid = $_GET['id'];
4 $info = '';
5 if(is_numeric($cid)){
6 $conn = mysql_connect('localhost','root','123456789') or $info = '数据库连接错误';
7 mysql_select_db('test',$conn) or $info = '数据库不存在';
8 if($oResult = mysql_query(" SELECT * FROM customers WHERE customerid = $cid") and mysql_num_rows($oResult) > 0){
9 $value = mysql_fetch_array($oResult);
10 $info = '姓名:'.$value['name'].' 地址:'.$value['address'];
11 mysql_free_result($oResult);
12 }else{
13 $info = '顾客ID不存在';
14 }
15 }else{
16 $info = '顾客ID不合法';
17 }
18 mysql_close($conn);
19 setcookie("info",$info);
20 header("Location:example.gif");
21  ?>

 

image.php
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2 <HTML>
3 <HEAD>
4 <TITLE> 获取顾客信息 </TITLE>
5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6 <script type="text/javascript">
7 function requestCustomerInfo(){
8 var cid = document.getElementById('cid').value;
9 var oImg = new Image();
10 oImg.onload = function(){
11 var returnStr = getCookie('info')?getCookie('info'):'找不到cookie';
12 displayCustomerInfo(returnStr);
13 deleteCookie('info');
14 };
15 oImg.onerror = function(){
16 displayCustomerInfo('一个错误出现了');
17 };
18 oImg.src = 'getcusdata.php?id='+cid;
19 }
20
21 function getCookie(str){
22 var sRe = "(?:;)?" + encodeURIComponent(str) + '=([^;]*);?';
23 var oRe = new RegExp(sRe);
24 if(oRe.test(document.cookie)){
25 return decodeURIComponent(RegExp["$1"]);
26 }else{
27 return null;
28 }
29 }
30
31 function deleteCookid(str){
32 document.cookie = encodeURIComponent(str) +"=0; "+"expires=Thu,1 Jan 1970 00:00:00 UTC; path=/";
33 }
34
35 function displayCustomerInfo(str){
36 var returnInfo = document.getElementById('returnInfo');
37 returnInfo.innerHTML = str;
38 }
39 </script>
40 </HEAD>
41 <BODY>
42 <input type="text" id="cid" />
43 <input type="button" value="查看顾客信息" onclick="requestCustomerInfo()" />
44 <div id="returnInfo"></div>
45 </BODY>
46 </HTML>

上面一例是通过设置浏览器cookie返回信息,还有另一种是查看加载图像的宽高,通过服务器脚本创建个不一样的宽高,比如1*1,2*2,3*3。然后在图像加载完后,做判断,然后输出返回信息。

posted on 2010-05-22 03:34  kingQueenyun  阅读(221)  评论(0编辑  收藏  举报

导航