在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 更小.更快,更易解析. ...
随机推荐
- jenkins+ant+jmeter接口自动化测试(持续构建)
使用badboy录制脚本,到处到jmeter后进行接口自动化,后来想着 可不可以用自动化来跑脚本呢,不用jmeter的图形界面呢, 选择了ant来进行构建,最后想到了用Jenkins来进行持续构建接口 ...
- log4j日志框架学习
初识Log4j: log4j有三个部分: 1.loggers 负责捕获日志信息. 2.appenders 负责输出信息到不同的目的地 ...
- 认清Javascript的地位并编写合理的Javascript代码
作为前端程序员,一定要认清javascript的地位,不要被它乱七八糟的特点所迷惑.JavaScript主要是用来操控和重新调整DOM,通过修改DOM结构,从而达到修改页面效果的目的. 要用这个中心思 ...
- 利用wireshark任意获取qq好友IP实施精准定位
没事玩一把,感觉还挺有趣,首先打开wireshark: 不管你连接的什么网,如图我连接的是WLAN,双击进入如图界面: ctrl-f进行搜索:如图 选择分组详情,字符串,并输入020048.这时候你就 ...
- 移动端iOS阻止橡皮筋效果
一.遇到的问题 移动端开发中,iOS的微信浏览器也好.Safari也好在浏览网页的时候会出现橡皮筋效果.就是当页面拉到尽头的时候还能再继续拉动,露出浏览器的底色,松手会回弹回去. 微信浏览器: Saf ...
- js学习--变量作用域和作用域链
作为一名菜鸟的我,每天学点的感觉还是不错的.今天学习闭包的过程中看到作用域与作用域链这两个概念,我觉得作为一名有追求的小白,有必要详细了解下. 变量的作用域 就js变量而言,有全局变量和局部变量.这里 ...
- MySQL(九)之数据表的查询详解(SELECT语法)二
上一篇讲了比较简单的单表查询以及MySQL的组函数,这一篇给大家分享一点比较难得知识了,关于多表查询,子查询,左连接,外连接等等.希望大家能都得到帮助! 在开始之前因为要多表查询,所以搭建好环境: 1 ...
- dispatch emit broadcast
1.broadcast 事件广播 遍历寻找所有子孙组件,假如子孙组件和componentName组件名称相同的话,则触发$emit的事件方法,数据为 params. 如果没有找到 则使用递归的方式 继 ...
- 最近找java实习面试被问到的东西总结(Java方向)
时间,就是这么很悄悄的溜走了将近两个年华,不知不觉的,研二了,作为一个一般学校的研究生,不知道该说自己是不学无术,还是说有过努力,反正,这两年里,有过坚持,有过堕落,这不,突然间,有种开窍的急迫感,寻 ...
- tkinter第一章1
tk1 ------------------------------------------------------------------------------------------ impor ...