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

    记录一下MyBatis的几个模块大纲,除去缓存以及集合映射两个部分 Mybatis架构 1. mybatis配置 SqlMapConfig.xml,此文件作为mybatis的全局配置文件,配置了myb ...

  2. 2017年8月28日 HTML/CSS 语法(待填坑)

    今天这种节日真的是 ----------------------------------------------------------- HTML  

  3. Java基础---继承、抽象、接口

    一.概述         继承是面向对象的一个重要特征.当多个类中存在相同属性和行为时,将这些内容抽取到单独一个类中,那么多个类无需再定义这些属性和行为,只要继那个类即可.这时,多个类可以称为子类,单 ...

  4. 一文教你迅速解决分布式事务 XA 一致性问题

    欢迎大家前往腾讯云技术社区,获取更多腾讯海量技术实践干货哦~ 作者:腾讯云数据库团队 近日,腾讯云发布了分布式数据库解决方案(DCDB),其最明显的特性之一就是提供了高于开源分布式事务XA的性能.大型 ...

  5. Groovy Script in SoapUI REST Testing

    1. Run special step: testRunner.runTestStepByName("stepName/requestName") get it's respons ...

  6. 对The C programming language一书第6.6节代码的理解

    代码如下(基本与书中一致) 1 #include <stdio.h> 2 #include <string.h> 3 #include <ctype.h> 4 #i ...

  7. Maven maven-compiler-plugin版本

    项目执行Maven clean后出现WARNING提示.报如信息如下,根据报错信息 'build.plugins.plugin.version' for org.apache.maven.plugin ...

  8. javascript学习笔记-3

    1.对于javascript中的this关键字,表示的是当前代码所处的对象. var a={ get:function(){ this.val=12 } } console.log(a.val); a ...

  9. JavaScript--我发现,原来你是这样的JS(基础概念--躯壳,不妨从中文角度看js)

    介绍 这是红宝书(JavaScript高级程序设计 3版)的读书笔记第二篇(基础概念--躯壳篇),有着部分第三章的知识内容,当然其中还有我个人的理解.红宝书这本书可以说是难啃的,要看完不容易,挺厚的, ...

  10. 总结各种排序算法【Java实现】

    一.插入类排序 1.直接插入排序 思想:将第i个插入到前i-1个中的适当位置 时间复杂度:T(n) = O(n²). 空间复杂度:S(n) = O(1). 稳定性:稳定排序. 如果碰见一个和插入元素相 ...