常常在百度搜索框輸入一部分關鍵詞後,彈出候選關鍵熱詞。如今咱們就用Ajax技術來實現這一功能。javascript
1、下載json.js文件php
百度搜一下,最好到json官網下載,安全起見。html
並與新建的兩個文件部署如圖java
json.js也可直接複製此處的代碼獲取。git
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 }
2、客戶端(suggest.html)redis
建立一個基於POST請求類型的Ajax項目頁面suggest.htmlexpress
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>
3、服務端(suggest.php)json
建立一個基於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 ?>
輸出結果:瀏覽器