在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 更小.更快,更易解析. ...
随机推荐
- JavaScript封装一个实用的select控件
最近一直把精力放在项目上面,导致忽略的一些底层的东西.以前就一直觉得原有的select控件很丑,正好周末有时间,试着做了一个简单封装,实现了它的基本功能.我总结了一下,大概分为三个部分: 1.对显示样 ...
- 原生Jdbc操作Mysql数据库开发步骤
原生Jdbc操作Mysql数据库开发步骤 原生的Jdbc就是指,不使用任何框架,仅用java.sql包下的方法实现数据库查询等的操作. 下面是开发步骤: 1.导入数据库驱动包 ...
- 阿里 java学习之路
https://maimai.cn/article/detail?fid=96107193&push_id=5603&share_user=http%3A%2F%2Fi9.taou.c ...
- 对 响应数据写在config文件的再次优化
之前写过 [基于moco的mock server 简单应用]这篇文章,然后自己这段时间也在做基金的接口测试,逛了一些论坛,然后对 响应数据写在config文件的再次优化,之前是把所有的响应数据都写到c ...
- 简单易学的SSM(Spring+SpringMVC+MyBatis)整合
SSM(Spring+SpringMVC+MyBatis)的整合: 具体执行过程:1.用户在页面向后台发送一个请求 2.请求由DispatcherServlet 前端控制器拦截交给SpringMVC管 ...
- java的jar包加密
由于项目要求(虽然我觉得代码没什么机密可言...),写好的jar包需要做一定加密处理 这里提供两种办法,一种奇葩,一种通用 1. 直接修改jar文件: 具体步骤: 在代码中插入一段不会运行的到的代码 ...
- ActiveMQ笔记——技术点汇总
目录 · Introduction to ActiveMQ · Installing ActiveMQ · Message-oriented middleware · JMS specificatio ...
- [译] 反思 1 号进程 / Rethinking PID 1
By Lennart Poettering 译 SReadFox 原文链接:http://0pointer.de/blog/projects/systemd.html 译注:笔者大约在 2011 年读 ...
- 图片懒加载Demo
相关知识: [js获取元素位置+元素大小]全面总结
- Spring Boot + Dubbo 可运行的例子源码-实现服务注册和远程调用
最近公司的一个分布式系统想要尝试迁移到Dubbo,项目本身是Spring Boot的,经过一些努力,最终也算是搭建起一个基础的框架了,放到这里记录一下.需要依赖一个外部的zookeeper. 源码地址 ...