在JavaScript中使用json.js:Ajax项目之POST请求(异步)
经常在百度搜索框输入一部分关键词后,弹出候选关键热词。现在我们就用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请求(异步)的更多相关文章
- 在JavaScript中使用json.js:使得js数组转为JSON编码
在json的官网中下载json.js,然后在script中引入,以使用json.js提供的两个关键方法. 1.数组对象.toJSONString() 这个方法将返回一个JSON编码格式的字符串,用来表 ...
- 在JavaScript中使用json.js:Ajax项目之GET请求(同步)
1.用php编写一个提供数据的响应程序(phpdata.php) <?php $arr=array(1,2,3,4); //将数组编码为JSON格式的数据 $jsonarr=json_encod ...
- 在JavaScript中使用json.js:访问JSON编码的某个值
演示: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3. ...
- JavaScript中使用JSON,即JS操作JSON总结
JSON(JavaScript Object Notation 对象标记) 是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,是理想的数据交换格式.同时,JSON是 JavaScript 原生 ...
- 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 ...
- python3开发进阶-Djamgo框架中的JSON和AJAX
阅读目录 什么是JSON 什么是AJAX AJAX常见的应用情景 jQery实现AJAX AJAX请求如何设置csrf_token AJAX上传文件 补充Django内置的serializers 一. ...
- Java和JavaScript中使用Json方法大全
林炳文Evankaka原创作品. 转载请注明出处http://blog.csdn.net/evankaka 摘要:JSON(JavaScript Object Notation) 是一种轻量级的数 ...
- Json学习总结(1)——Java和JavaScript中使用Json方法大全
摘要:JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. JSON采用完全独立于语言的文本格式,但是也使用了类似于C语 ...
- 简单使用JSON,JavaScript中创建 JSON 对象(一)
JSON:JavaScript 对象表示法(JavaScript Object Notation). JSON 是存储和交换文本信息的语法.类似 XML. JSON 比 XML 更小.更快,更易解析. ...
随机推荐
- redis 介绍和常用命令
redis 介绍和常用命令 redis简介 Redis 是一款开源的,基于 BSD 许可的,高级键值 (key-value) 缓存 (cache) 和存储 (store) 系统.由于 Redis 的键 ...
- [2017-08-21]Abp系列——如何使用Abp插件机制(注册权限、菜单、路由)
本系列目录:Abp介绍和经验分享-目录 Abp的模块系统支持插件机制,可以在指定目录中放置模块程序集,然后应用程序启动时会搜索该目录,加载其中所有程序集中的模块. 如何使用这套机制进行功能插件化开发? ...
- sizeof(void)有什么用
偶然发现在C中sizeof(void)是合法的,于是,对它的作用产生了疑问.查阅资料在GNU文档中发现如下解释: In GNU C, addition and subtraction operatio ...
- 新的表格展示利器 Bootstrap Table Ⅱ
上一篇文章介绍了Bootstrap Table的基本知识点和应用,本文针对上一篇文章中未解决的文件导出问题进行分析,同时介绍BootStrap Table的扩展功能,当行表格数据修改. 1.B ...
- CAS 单点登陆
一.Tomcat配置SSL 1. 生成 server key 以命令方式换到目录%TOMCAT_HOME%,在command命令行输入如下命令: keytool -genkey -alias tomc ...
- flex弹性布局学习
一.介绍 flex( flexible box:弹性布局盒模型),是2009年w3c提出的一种可以简洁.快速弹性布局的属性.主要思想是给予容器控制内部元素高度和宽度的能力.目前已得到以下浏览器支持: ...
- Error Handling in ASP.NET Core
Error Handling in ASP.NET Core 前言 在程序中,经常需要处理比如 404,500 ,502等错误,如果直接返回错误的调用堆栈的具体信息,显然大部分的用户看到是一脸懵逼的 ...
- Spring bean中的properties元素内的name 和 ref都代表什么意思啊?
<bean id="userAction" class="com.neusoft.gmsbs.gms.user.action.UserAction" sc ...
- 汇编指令-位置无关码(BL)与绝对位置码(LDR)(2)
位置无关码,即该段代码无论放在内存的哪个地址,都能正确运行.究其原因,是因为代码里没有使用绝对地址,都是相对地址. 位置相关码,即它的地址与代码处于的位置相关,是绝对地址 BL :带链接分支跳转指令 ...
- Linux-chmod命令(4)
chmod:(change mode)改变linux系统文件或目录的访问权限.用它控制文件或目录的访问权限. 格式 : [-cfvR][[+-=][rwxX]...][,...] 参数 1: -c ...