经常在百度搜索框输入一部分关键词后,弹出候选关键热词。现在我们就用Ajax技术来实现这一功能。

一、下载json.js文件

百度搜一下,最好到json官网下载,安全起见。

并与新建的两个文件部署如图

json.js也可直接复制此处的代码获取。

 /*
json.js
2008-03-14 Public Domain No warranty expressed or implied. Use at your own risk. This file has been superceded by http://www.JSON.org/json2.js See http://www.JSON.org/js.html This file adds these methods to JavaScript: array.toJSONString(whitelist)
boolean.toJSONString()
date.toJSONString()
number.toJSONString()
object.toJSONString(whitelist)
string.toJSONString()
These methods produce a JSON text from a JavaScript value.
It must not contain any cyclical references. Illegal values
will be excluded. The default conversion for dates is to an ISO string. You can
add a toJSONString method to any date object to get a different
representation. The object and array methods can take an optional whitelist
argument. A whitelist is an array of strings. If it is provided,
keys in objects not found in the whitelist are excluded. string.parseJSON(filter)
This method parses a JSON text to produce an object or
array. It can throw a SyntaxError exception. The optional filter parameter is a function which can filter and
transform the results. It receives each of the keys and values, and
its return value is used instead of the original value. If it
returns what it received, then structure is not modified. If it
returns undefined then the member is deleted. Example: // Parse the text. If a key contains the string 'date' then
// convert the value to a date. myData = text.parseJSON(function (key, value) {
return key.indexOf('date') >= 0 ? new Date(value) : value;
}); It is expected that these methods will formally become part of the
JavaScript Programming Language in the Fourth Edition of the
ECMAScript standard in 2008. This file will break programs with improper for..in loops. See
http://yuiblog.com/blog/2006/09/26/for-in-intrigue/ This is a reference implementation. You are free to copy, modify, or
redistribute. Use your own copy. It is extremely unwise to load untrusted third party
code into your pages.
*/ /*jslint evil: true */ /*members "\b", "\t", "\n", "\f", "\r", "\"", "\\", apply, charCodeAt,
floor, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes,
getUTCMonth, getUTCSeconds, hasOwnProperty, join, length, parseJSON,
prototype, push, replace, test, toJSONString, toString
*/ // Augment the basic prototypes if they have not already been augmented. if (!Object.prototype.toJSONString) { Array.prototype.toJSONString = function (w) {
var a = [], // The array holding the partial texts.
i, // Loop counter.
l = this.length,
v; // The value to be stringified. // For each value in this array... for (i = 0; i < l; i += 1) {
v = this[i];
switch (typeof v) {
case 'object': // Serialize a JavaScript object value. Treat objects thats lack the
// toJSONString method as null. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case. if (v && typeof v.toJSONString === 'function') {
a.push(v.toJSONString(w));
} else {
a.push('null');
}
break; case 'string':
case 'number':
case 'boolean':
a.push(v.toJSONString());
break;
default:
a.push('null');
}
} // Join all of the member texts together and wrap them in brackets. return '[' + a.join(',') + ']';
}; Boolean.prototype.toJSONString = function () {
return String(this);
}; Date.prototype.toJSONString = function () { // Eventually, this method will be based on the date.toISOString method. function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n;
} return '"' + this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z"';
}; Number.prototype.toJSONString = function () { // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(this) ? String(this) : 'null';
}; Object.prototype.toJSONString = function (w) {
var a = [], // The array holding the partial texts.
k, // The current key.
i, // The loop counter.
v; // The current value. // If a whitelist (array of keys) is provided, use it assemble the components
// of the object. if (w) {
for (i = 0; i < w.length; i += 1) {
k = w[i];
if (typeof k === 'string') {
v = this[k];
switch (typeof v) {
case 'object': // Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case. if (v) {
if (typeof v.toJSONString === 'function') {
a.push(k.toJSONString() + ':' +
v.toJSONString(w));
}
} else {
a.push(k.toJSONString() + ':null');
}
break; case 'string':
case 'number':
case 'boolean':
a.push(k.toJSONString() + ':' + v.toJSONString()); // Values without a JSON representation are ignored. }
}
}
} else { // Iterate through all of the keys in the object, ignoring the proto chain
// and keys that are not strings. for (k in this) {
if (typeof k === 'string' &&
Object.prototype.hasOwnProperty.apply(this, [k])) {
v = this[k];
switch (typeof v) {
case 'object': // Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case. if (v) {
if (typeof v.toJSONString === 'function') {
a.push(k.toJSONString() + ':' +
v.toJSONString());
}
} else {
a.push(k.toJSONString() + ':null');
}
break; case 'string':
case 'number':
case 'boolean':
a.push(k.toJSONString() + ':' + v.toJSONString()); // Values without a JSON representation are ignored. }
}
}
} // Join all of the member texts together and wrap them in braces. return '{' + a.join(',') + '}';
}; (function (s) { // Augment String.prototype. We do this in an immediate anonymous function to
// avoid defining global variables. // m is a table of character substitutions. var m = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
}; s.parseJSON = function (filter) {
var j; function walk(k, v) {
var i, n;
if (v && typeof v === 'object') {
for (i in v) {
if (Object.prototype.hasOwnProperty.apply(v, [i])) {
n = walk(i, v[i]);
if (n !== undefined) {
v[i] = n;
} else {
delete v[i];
}
}
}
}
return filter(k, v);
} // Parsing happens in three stages. In the first stage, we run the text against
// a regular expression which looks for non-JSON characters. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we will reject all
// unexpected characters. // We split the first stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace all backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/.test(this.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the second stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity. j = eval('(' + this + ')'); // In the optional third stage, we recursively walk the new structure, passing
// each name/value pair to a filter function for possible transformation. return typeof filter === 'function' ? walk('', j) : j;
} // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('parseJSON');
}; s.toJSONString = function () { // If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences. if (/["\\\x00-\x1f]/.test(this)) {
return '"' + this.replace(/[\x00-\x1f\\"]/g, function (a) {
var c = m[a];
if (c) {
return c;
}
c = a.charCodeAt();
return '\\u00' + Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}) + '"';
}
return '"' + this + '"';
};
})(String.prototype);
}

json.js

二、客户端(suggest.html)

创建一个基于POST请求类型的Ajax项目页面suggest.html

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="json.js"></script>
<script type="text/javascript">
//为XHR对象创建全局变量
var xhr; function getXHR(){//获取跨浏览器的XmlHttpRequest对象
var req;
if (window.XMLHttpRequest) {
req= new XMLHttpRequest();
}else if(window.ActiveXObject){
req= new ActiveXObject("Microsoft.XMLHTTP");
}
return req;
} function suggest(){
//如果还有未处理完的XHR请求正在进行,就中断它
if (xhr && xhr.readyState !=0) {
xhr.abort();
} xhr=getXHR(); //创建异步POST请求(根据需求,修改这行代码)
xhr.open("POST","suggest.php",true); //读取搜索框中的值
searchValue=document.getElementById("search").value; //以URL编码格式编码数据
data="search="+ encodeURIComponent(searchValue); //定义接收状态变更通知的函数
xhr.onreadystatechange=readyStateChange; //设置请求头信息,以便让PHP知道这是一个表单提交
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //将数据传送到服务器上
xhr.send(data);
} function readyStateChange(){
//状态4表示数据已经准备好了
if (xhr.readyState==4) { //检查服务器是否发送了数据,并且请求是200OK
if (xhr.responseText && xhr.status==200) {
json=xhr.responseText; //解析服务器的响应内容,创建一个JS数组
try{
suggestionArr=json.parseJSON();
}catch(e){
//解析数据遇到问题
alert("解析数据遇到问题");
} //创建一些HTML文本
tmpHtml="";
for (i=0;i<suggestionArr.length;i++) {
tmpHtml+= suggestionArr[i]+"<br />";
} div=document.getElementById("suggestions");
div.innerHTML=tmpHtml;
}
}
} </script>
</head>
<body>
<input id="search" type="text" onkeyup="suggest()"/>
<div id="suggestions"></div>
</body>
</html>

suggest.html

三、服务端(suggest.php)

创建一个基于POST请求类型的Ajax项目程序suggest.php

 <?php
$arr=array(
'zhangsan','lisi',
'wangwu','zhaoliu',
'andy','admin','安迪'
); $search=strtolower($_POST['search']); $hits=array();
if (!empty($search)) {
foreach ($arr as $name) {
if (strpos(strtolower($name),$search)===0) {
$hits[]=$name;
}
}
} echo json_encode($hits);
?>

suggest.php

输出结果:

在JavaScript中使用json.js:Ajax项目之POST请求(异步)的更多相关文章

  1. 在JavaScript中使用json.js:使得js数组转为JSON编码

    在json的官网中下载json.js,然后在script中引入,以使用json.js提供的两个关键方法. 1.数组对象.toJSONString() 这个方法将返回一个JSON编码格式的字符串,用来表 ...

  2. 在JavaScript中使用json.js:Ajax项目之GET请求(同步)

    1.用php编写一个提供数据的响应程序(phpdata.php) <?php $arr=array(1,2,3,4); //将数组编码为JSON格式的数据 $jsonarr=json_encod ...

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

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

  4. JavaScript中使用JSON,即JS操作JSON总结

    JSON(JavaScript Object Notation 对象标记) 是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,是理想的数据交换格式.同时,JSON是 JavaScript 原生 ...

  5. JavaScript中解析JSON --- json.js 、 json2.js 以及 json3.js的使用区别

    JSON官方(http://www.json.org/)提供了一个json.js,json.js是JSON官方提供的在JavaScript中解析JSON的js包,json.js.json2.js.js ...

  6. python3开发进阶-Djamgo框架中的JSON和AJAX

    阅读目录 什么是JSON 什么是AJAX AJAX常见的应用情景 jQery实现AJAX AJAX请求如何设置csrf_token AJAX上传文件 补充Django内置的serializers 一. ...

  7. Java和JavaScript中使用Json方法大全

    林炳文Evankaka原创作品. 转载请注明出处http://blog.csdn.net/evankaka   摘要:JSON(JavaScript Object Notation) 是一种轻量级的数 ...

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

    摘要:JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. JSON采用完全独立于语言的文本格式,但是也使用了类似于C语 ...

  9. 简单使用JSON,JavaScript中创建 JSON 对象(一)

    JSON:JavaScript 对象表示法(JavaScript Object Notation). JSON 是存储和交换文本信息的语法.类似 XML. JSON 比 XML 更小.更快,更易解析. ...

随机推荐

  1. python基础学习(十二)

    模块 前面有简单介绍如何使用import从外部模块获取函数并且为自己的程序所用: >>> import math >>> math.sin(0) #sin为正弦函数 ...

  2. snowflake主键生成策略

    1.snowflake简介 在分布式系统中,我们需要各种各样的ID,既然是ID那么必然是要保证全局唯一,除此之外,不同当业务还需要不同的特性,比如像并发巨大的业务要求ID生成效率高,吞吐大:比如某些银 ...

  3. 互联网世界中的C语言——我的golang学习笔记:1(基础语法快速过)

    前言 学习任何知识都会有一个学习背景 最近,我们团队乃至我司整个云服务,上go的呼声越来越高!新服务已经开始用go开发,部分现有Java版的服务重构为go也只是时间问题而已,故相关技术积累势在必行!在 ...

  4. c语言中的文件格式化读写函数fscanf和fprintf函数

    很多时候我们需要写入数据到文件中时都觉得很困扰,因为格式乱七八槽的,可读性太差了,于是我们就想有没有什么函数可以格式化的从文件中输入和输出呢,还真有.下面我将讲解一下fscanf和fprintf的强大 ...

  5. 初遇.net

    初遇.net 为了自己的理想我选择了.net课程进行自我提升,想想以后能成为一位程序猿不由得有点兴奋呢,还有另一件高兴的事是我认识了十几位来自不同区县的老师同学,都说人脉就是财富,是不是我的财富有多了 ...

  6. chrome开发工具指南(十一)

    检查资源 使用 Application 面板的 Frames 窗格可以按框架组织资源. 您也可以在 Sources 面板中停用 Group by folder 选项,按框架查看资源. 要按网域和文件夹 ...

  7. 操作系统-实验一、DOS使用命令实验

    实验一.DOS使用命令实验 一.实验目的      DOS是市场上早期获得巨大成功的桌面操作系统,现在很多同学都不太熟悉.本实验的目的就是让同学们读者从操作系统理论的观点来重新认识它们,了解和掌握DO ...

  8. Kafka Streams 剖析

    1.概述 Kafka Streams 是一个用来处理流式数据的库,属于Java类库,它并不是一个流处理框架,和Storm,Spark Streaming这类流处理框架是明显不一样的.那这样一个库是做什 ...

  9. Project 9:两种简单数列排序

    1.冒泡法排序 /* 冒泡排序法的核心思想就是依次把最大的数换到最后面. 若有n个数 就需要通过n-1次循环来排序. 具体做法就是从第一个数开始 两个数比较大小大的换到后面,这样最大的就在最后了. 然 ...

  10. Java GUI+mysql+分页查询

    1.要求 : 创建一个学生信息管理数据库 2.实现分页查询 代码如下: a)学生实体类: /** * @author: Annie * @date:2016年6月23日 * @description: ...