经常在百度搜索框输入一部分关键词后,弹出候选关键热词。现在我们就用Ajax技术来实现这一功能。
一、下载json.js文件
百度搜一下,最好到json官网下载,安全起见。
并与新建的两个文件部署如图
json.js也可直接复制此处的代码获取。
1 /* 2 json.js 3 2008-03-14 4 5 Public Domain 6 7 No warranty expressed or implied. Use at your own risk. 8 9 This file has been superceded by http://www.JSON.org/json2.js 10 11 See http://www.JSON.org/js.html 12 13 This file adds these methods to JavaScript: 14 15 array.toJSONString(whitelist) 16 boolean.toJSONString() 17 date.toJSONString() 18 number.toJSONString() 19 object.toJSONString(whitelist) 20 string.toJSONString() 21 These methods produce a JSON text from a JavaScript value. 22 It must not contain any cyclical references. Illegal values 23 will be excluded. 24 25 The default conversion for dates is to an ISO string. You can 26 add a toJSONString method to any date object to get a different 27 representation. 28 29 The object and array methods can take an optional whitelist 30 argument. A whitelist is an array of strings. If it is provided, 31 keys in objects not found in the whitelist are excluded. 32 33 string.parseJSON(filter) 34 This method parses a JSON text to produce an object or 35 array. It can throw a SyntaxError exception. 36 37 The optional filter parameter is a function which can filter and 38 transform the results. It receives each of the keys and values, and 39 its return value is used instead of the original value. If it 40 returns what it received, then structure is not modified. If it 41 returns undefined then the member is deleted. 42 43 Example: 44 45 // Parse the text. If a key contains the string ‘date‘ then 46 // convert the value to a date. 47 48 myData = text.parseJSON(function (key, value) { 49 return key.indexOf(‘date‘) >= 0 ? new Date(value) : value; 50 }); 51 52 It is expected that these methods will formally become part of the 53 JavaScript Programming Language in the Fourth Edition of the 54 ECMAScript standard in 2008. 55 56 This file will break programs with improper for..in loops. See 57 http://yuiblog.com/blog/2006/09/26/for-in-intrigue/ 58 59 This is a reference implementation. You are free to copy, modify, or 60 redistribute. 61 62 Use your own copy. It is extremely unwise to load untrusted third party 63 code into your pages. 64 */ 65 66 /*jslint evil: true */ 67 68 /*members "\b", "\t", "\n", "\f", "\r", "\"", "\\", apply, charCodeAt, 69 floor, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, 70 getUTCMonth, getUTCSeconds, hasOwnProperty, join, length, parseJSON, 71 prototype, push, replace, test, toJSONString, toString 72 */ 73 74 // Augment the basic prototypes if they have not already been augmented. 75 76 if (!Object.prototype.toJSONString) { 77 78 Array.prototype.toJSONString = function (w) { 79 var a = [], // The array holding the partial texts. 80 i, // Loop counter. 81 l = this.length, 82 v; // The value to be stringified. 83 84 // For each value in this array... 85 86 for (i = 0; i < l; i += 1) { 87 v = this[i]; 88 switch (typeof v) { 89 case ‘object‘: 90 91 // Serialize a JavaScript object value. Treat objects thats lack the 92 // toJSONString method as null. Due to a specification error in ECMAScript, 93 // typeof null is ‘object‘, so watch out for that case. 94 95 if (v && typeof v.toJSONString === ‘function‘) { 96 a.push(v.toJSONString(w)); 97 } else { 98 a.push(‘null‘); 99 } 100 break; 101 102 case ‘string‘: 103 case ‘number‘: 104 case ‘boolean‘: 105 a.push(v.toJSONString()); 106 break; 107 default: 108 a.push(‘null‘); 109 } 110 } 111 112 // Join all of the member texts together and wrap them in brackets. 113 114 return ‘[‘ + a.join(‘,‘) + ‘]‘; 115 }; 116 117 118 Boolean.prototype.toJSONString = function () { 119 return String(this); 120 }; 121 122 123 Date.prototype.toJSONString = function () { 124 125 // Eventually, this method will be based on the date.toISOString method. 126 127 function f(n) { 128 129 // Format integers to have at least two digits. 130 131 return n < 10 ? ‘0‘ + n : n; 132 } 133 134 return ‘"‘ + this.getUTCFullYear() + ‘-‘ + 135 f(this.getUTCMonth() + 1) + ‘-‘ + 136 f(this.getUTCDate()) + ‘T‘ + 137 f(this.getUTCHours()) + ‘:‘ + 138 f(this.getUTCMinutes()) + ‘:‘ + 139 f(this.getUTCSeconds()) + ‘Z"‘; 140 }; 141 142 143 Number.prototype.toJSONString = function () { 144 145 // JSON numbers must be finite. Encode non-finite numbers as null. 146 147 return isFinite(this) ? String(this) : ‘null‘; 148 }; 149 150 151 Object.prototype.toJSONString = function (w) { 152 var a = [], // The array holding the partial texts. 153 k, // The current key. 154 i, // The loop counter. 155 v; // The current value. 156 157 // If a whitelist (array of keys) is provided, use it assemble the components 158 // of the object. 159 160 if (w) { 161 for (i = 0; i < w.length; i += 1) { 162 k = w[i]; 163 if (typeof k === ‘string‘) { 164 v = this[k]; 165 switch (typeof v) { 166 case ‘object‘: 167 168 // Serialize a JavaScript object value. Ignore objects that lack the 169 // toJSONString method. Due to a specification error in ECMAScript, 170 // typeof null is ‘object‘, so watch out for that case. 171 172 if (v) { 173 if (typeof v.toJSONString === ‘function‘) { 174 a.push(k.toJSONString() + ‘:‘ + 175 v.toJSONString(w)); 176 } 177 } else { 178 a.push(k.toJSONString() + ‘:null‘); 179 } 180 break; 181 182 case ‘string‘: 183 case ‘number‘: 184 case ‘boolean‘: 185 a.push(k.toJSONString() + ‘:‘ + v.toJSONString()); 186 187 // Values without a JSON representation are ignored. 188 189 } 190 } 191 } 192 } else { 193 194 // Iterate through all of the keys in the object, ignoring the proto chain 195 // and keys that are not strings. 196 197 for (k in this) { 198 if (typeof k === ‘string‘ && 199 Object.prototype.hasOwnProperty.apply(this, [k])) { 200 v = this[k]; 201 switch (typeof v) { 202 case ‘object‘: 203 204 // Serialize a JavaScript object value. Ignore objects that lack the 205 // toJSONString method. Due to a specification error in ECMAScript, 206 // typeof null is ‘object‘, so watch out for that case. 207 208 if (v) { 209 if (typeof v.toJSONString === ‘function‘) { 210 a.push(k.toJSONString() + ‘:‘ + 211 v.toJSONString()); 212 } 213 } else { 214 a.push(k.toJSONString() + ‘:null‘); 215 } 216 break; 217 218 case ‘string‘: 219 case ‘number‘: 220 case ‘boolean‘: 221 a.push(k.toJSONString() + ‘:‘ + v.toJSONString()); 222 223 // Values without a JSON representation are ignored. 224 225 } 226 } 227 } 228 } 229 230 // Join all of the member texts together and wrap them in braces. 231 232 return ‘{‘ + a.join(‘,‘) + ‘}‘; 233 }; 234 235 236 (function (s) { 237 238 // Augment String.prototype. We do this in an immediate anonymous function to 239 // avoid defining global variables. 240 241 // m is a table of character substitutions. 242 243 var m = { 244 ‘\b‘: ‘\\b‘, 245 ‘\t‘: ‘\\t‘, 246 ‘\n‘: ‘\\n‘, 247 ‘\f‘: ‘\\f‘, 248 ‘\r‘: ‘\\r‘, 249 ‘"‘ : ‘\\"‘, 250 ‘\\‘: ‘\\\\‘ 251 }; 252 253 254 s.parseJSON = function (filter) { 255 var j; 256 257 function walk(k, v) { 258 var i, n; 259 if (v && typeof v === ‘object‘) { 260 for (i in v) { 261 if (Object.prototype.hasOwnProperty.apply(v, [i])) { 262 n = walk(i, v[i]); 263 if (n !== undefined) { 264 v[i] = n; 265 } else { 266 delete v[i]; 267 } 268 } 269 } 270 } 271 return filter(k, v); 272 } 273 274 275 // Parsing happens in three stages. In the first stage, we run the text against 276 // a regular expression which looks for non-JSON characters. We are especially 277 // concerned with ‘()‘ and ‘new‘ because they can cause invocation, and ‘=‘ 278 // because it can cause mutation. But just to be safe, we will reject all 279 // unexpected characters. 280 281 // We split the first stage into 4 regexp operations in order to work around 282 // crippling inefficiencies in IE‘s and Safari‘s regexp engines. First we 283 // replace all backslash pairs with ‘@‘ (a non-JSON character). Second, we 284 // replace all simple value tokens with ‘]‘ characters. Third, we delete all 285 // open brackets that follow a colon or comma or that begin the text. Finally, 286 // we look to see that the remaining characters are only whitespace or ‘]‘ or 287 // ‘,‘ or ‘:‘ or ‘{‘ or ‘}‘. If that is so, then the text is safe for eval. 288 289 if (/^[\],:{}\s]*$/.test(this.replace(/\\["\\\/bfnrtu]/g, ‘@‘). 290 replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ‘]‘). 291 replace(/(?:^|:|,)(?:\s*\[)+/g, ‘‘))) { 292 293 // In the second stage we use the eval function to compile the text into a 294 // JavaScript structure. The ‘{‘ operator is subject to a syntactic ambiguity 295 // in JavaScript: it can begin a block or an object literal. We wrap the text 296 // in parens to eliminate the ambiguity. 297 298 j = eval(‘(‘ + this + ‘)‘); 299 300 // In the optional third stage, we recursively walk the new structure, passing 301 // each name/value pair to a filter function for possible transformation. 302 303 return typeof filter === ‘function‘ ? walk(‘‘, j) : j; 304 } 305 306 // If the text is not JSON parseable, then a SyntaxError is thrown. 307 308 throw new SyntaxError(‘parseJSON‘); 309 }; 310 311 312 s.toJSONString = function () { 313 314 // If the string contains no control characters, no quote characters, and no 315 // backslash characters, then we can simply slap some quotes around it. 316 // Otherwise we must also replace the offending characters with safe 317 // sequences. 318 319 if (/["\\\x00-\x1f]/.test(this)) { 320 return ‘"‘ + this.replace(/[\x00-\x1f\\"]/g, function (a) { 321 var c = m[a]; 322 if (c) { 323 return c; 324 } 325 c = a.charCodeAt(); 326 return ‘\\u00‘ + Math.floor(c / 16).toString(16) + 327 (c % 16).toString(16); 328 }) + ‘"‘; 329 } 330 return ‘"‘ + this + ‘"‘; 331 }; 332 })(String.prototype); 333 }
json.js
二、客户端(suggest.html)
创建一个基于POST请求类型的Ajax项目页面suggest.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <script type="text/javascript" src="json.js"></script> 5 <script type="text/javascript"> 6 //为XHR对象创建全局变量 7 var xhr; 8 9 function getXHR(){//获取跨浏览器的XmlHttpRequest对象 10 var req; 11 if (window.XMLHttpRequest) { 12 req= new XMLHttpRequest(); 13 }else if(window.ActiveXObject){ 14 req= new ActiveXObject("Microsoft.XMLHTTP"); 15 } 16 return req; 17 } 18 19 function suggest(){ 20 //如果还有未处理完的XHR请求正在进行,就中断它 21 if (xhr && xhr.readyState !=0) { 22 xhr.abort(); 23 } 24 25 xhr=getXHR(); 26 27 //创建异步POST请求(根据需求,修改这行代码) 28 xhr.open("POST","suggest.php",true); 29 30 //读取搜索框中的值 31 searchValue=document.getElementById("search").value; 32 33 //以URL编码格式编码数据 34 data="search="+ encodeURIComponent(searchValue); 35 36 //定义接收状态变更通知的函数 37 xhr.onreadystatechange=readyStateChange; 38 39 //设置请求头信息,以便让PHP知道这是一个表单提交 40 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 41 42 //将数据传送到服务器上 43 xhr.send(data); 44 } 45 46 function readyStateChange(){ 47 //状态4表示数据已经准备好了 48 if (xhr.readyState==4) { 49 50 //检查服务器是否发送了数据,并且请求是200OK 51 if (xhr.responseText && xhr.status==200) { 52 json=xhr.responseText; 53 54 //解析服务器的响应内容,创建一个JS数组 55 try{ 56 suggestionArr=json.parseJSON(); 57 }catch(e){ 58 //解析数据遇到问题 59 alert("解析数据遇到问题"); 60 } 61 62 //创建一些HTML文本 63 tmpHtml=""; 64 for (i=0;i<suggestionArr.length;i++) { 65 tmpHtml+= suggestionArr[i]+"<br />"; 66 } 67 68 div=document.getElementById("suggestions"); 69 div.innerHTML=tmpHtml; 70 } 71 } 72 } 73 74 </script> 75 </head> 76 <body> 77 <input id="search" type="text" onkeyup="suggest()"/> 78 <div id="suggestions"></div> 79 </body> 80 </html>
suggest.html
三、服务端(suggest.php)
创建一个基于POST请求类型的Ajax项目程序suggest.php
1 <?php 2 $arr=array( 3 ‘zhangsan‘,‘lisi‘, 4 ‘wangwu‘,‘zhaoliu‘, 5 ‘andy‘,‘admin‘,‘安迪‘ 6 ); 7 8 $search=strtolower($_POST[‘search‘]); 9 10 $hits=array(); 11 if (!empty($search)) { 12 foreach ($arr as $name) { 13 if (strpos(strtolower($name),$search)===0) { 14 $hits[]=$name; 15 } 16 } 17 } 18 19 echo json_encode($hits); 20 ?>
suggest.php
输出结果:
时间: 2024-10-04 21:46:23