经常在百度搜索框输入一部分关键词后,弹出候选关键热词。现在我们就用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

输出结果:

转载于:https://www.cnblogs.com/andy9468/p/4243521.html

在JavaScript中使用json.js:Ajax项目之POST请求(异步)相关推荐

  1. 在JavaScript中使用json.js:访问JSON编码的某个值

    演示: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3. ...

  2. JS/JavaScript中解析JSON --- JSON.parse()、JSON.stringify()以及$.parseJSON()使用详解

    JS/JavaScript中解析JSON --- JSON.parse().JSON.stringify()以及$.parseJSON()使用详解 现在JSON格式在web开发中非常重要,特别是在使用 ...

  3. 在JavaScript中解析JSON? [重复]

    本文翻译自:Parse JSON in JavaScript? [duplicate] This question already has answers here : 这个问题已经在这里有了答案 : ...

  4. Json学习总结(1)——Java和JavaScript中使用Json方法大全

    2019独角兽企业重金招聘Python工程师标准>>> 摘要:JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript ...

  5. jsonp请求html页面,JavaScript中的JSON和JSONP

    简单地使用json并不能支持跨域资源请求,为了解决这个问题,需要采用jsonp数据交互协议.众所周知,js文件的调用不受跨域与否的限制,因此如果想通过纯web端跨域访问数据,只能在远程服务器上设法将j ...

  6. javascript 中使用JSON

    因为JSON 是 javascript 的一个子集,所以,在javascript 中使用JSON是非常简单的. js 代码 var myJSONObject = {"bindings&quo ...

  7. 在 JavaScript 中创建 JSON 对象

    <html> <body> <h2>在 JavaScript 中创建 JSON 对象</h2><p> Name: <span id=& ...

  8. JSON—JavaScript中的JSON

    JSON的数据格式 JavaScript中的JSON 1.JavaScript与JSON JSON是一种语法,用来序列化对象.数组.数值.字符串.布尔值 null.他基于JavaScript语法,但与 ...

  9. js判断json有没有某值_JS中判断JSON数据是否存在某字段的方法 JavaScript中判断json中是否有某个字段...

    方式一 !("key" in obj) 方式二 obj.hasOwnProperty("key")  //obj为json对象. 实例: var jsonwor ...

最新文章

  1. 如何用手机打开dcm格式图片_手机也能当扫描仪用?如何用手机扫描图片?
  2. 记录 Git命令速查表
  3. python中组合框_PyQt 组合框
  4. python随机生成字符串_如何随机生成大写字母和数字组成的字符串
  5. Jquery 操作select总结
  6. 作者:何波(1989-),男,就职于中国信息通信研究院互联网法律研究中心
  7. 如何让JSON只从Model中输出一部分
  8. java 数组 存储_Java-将数组存储到内存或从内存上传到磁盘
  9. 紧急!Log4j2 再再爆雷:刚升级,又连爆 “核弹级” 远程数据泄露 ! v2.17.0 横空出世。。。...
  10. 9. Javascript 表达式
  11. MyBatis动态SQL
  12. Kepp-alive的实际运用场景(1)
  13. 麻雀要革命2 第44节:怦然心动的星月童话
  14. 微服务架构通讯模式架构分析
  15. 自制AVA数据集工具/slowfast模型训练数据集制作
  16. android中的系统应用
  17. arduino声音传感器与二极管_如何将声音传感器与Arduino连接 并实现继电器控制项目...
  18. Netty 源码分析系列(十五)自定义解码器、编码器、编解码器
  19. 弥散磁共振成像在神经科学中的应用
  20. 数据分析案例 自行车公司

热门文章

  1. 微信小程序 navigator 用来实现页面跳转功能
  2. SQL查询单表数据(一)
  3. 清北学堂dp图论营游记day4
  4. django中遇到的错误并解决
  5. 4.6上午口语练习 阅读词汇
  6. cri-o 与 cni的集成分析
  7. erlang csv
  8. 数组----数组的拷贝、排序、遍历、引用,console交互
  9. Linux命令find查询suid和sgid
  10. Python_Proxy代理