1、概述
2、XMLHttpRequest 的方法和属性
XMLHttpRequest包含了基本的属性和方法,正是通过这些方法和属性实现了对服务器的通讯。Ajax依赖XMLHttpRequest完成与服务器的通信。
XMLHttpRequest的基本方法如下:
Abort():停止发送当前请求。
getAllResponseHeaders():获取服务器返回的全部响应头。
getResponseHeader(“headerLabel”):根据响应头的名字来获取响应头。
Open(“method”,”URL”,…):建立与服务器的连接,并设置请求的方法是否使用异步请求。如果远程服务需要用户名,密码,则提供。
Send(content):发送请求。
setRequestHeader(“label”,”values”):在发送请求之前,先设置请求头。
看代码 2/getAllResponseHeaders
XMLHttpRequest的属性如下:
1、 onreadystatechange:用于指定XMLHttpRequest对象状态改变时的事件处理函数。当XMLHttpRequest的状态放生改变时,该函数将被触发。XMLHttpRequest对象有如下几种状态:
0 :XMLHttpRequest对象还没有完成初始化;
1 :XMLHttpRequest对象开始发送请求;
2 :XMLHttpRequest对象的请求发送完成;
3 :XMLHttpRequest对象开始读取服务器的响应;
4 :XMLHttpRequest对象读取服务器响应结束。
2、 readyState: XMLHttpRequest对象的处理状态。
3、 responseText:用于获取服务器的响应文本。
4、 responseXML:用于获取服务器响应的XML文档对象。
5、 status:服务器返回的状态码,只有当服务器的响应已经完成时,才会有该状态码。
6、 statusText:服务器返回的状态文本信息,只有当服务器的响应已经完成时,才会有该状态文本信息。
看代码2/readyState反映的就是状态的变化过程。
注意:onreadystatechange属性在IE中可以不区分大小写,但是在非IE浏览器中,将严格区分大小写,只能写成onReadyStateChange的形式。
服务器响应完成后,依然不能直接获取服务器响应。应为服务器响应有多种情况。为了判断服务器响应是否正确,可以通过XMLHttpRequest对象的statue和statusText两个属性将上面HTML页面的回调函数改为如下形式:
function processResponse(){
if(xmlrequest.readyState == 4){
alert(xmlrequest.status + "\n"
+ xmlrequest.statusText);
}
}
该代码表示:当响应完成时,通过alert输出status和statusText的值。
含义
status:服务器响应的状态码;
statusText:服务器响应的状态提示;
服务器常用的状态码及其对应的含义如下:
200 服务器响应正常。
500 服务器内部错误。
结论:如果想通过JavaScript获取服务器响应,必须先判断服务器响应是否完成。判断服务器的响应是否完成,可以通过判断XMLHttpRequest对象的readyState属性进行。当readyState为4时,响应完成;服务器响应完成后,还应判断服务器响应是否正确。判断服务器响应是否正确,可以通过判断XMLHttpRequest的status是否为200来完成。
3、发送请求
Ajax与传统Web应用的最大区别在于:发送请求的方式。传统web应用采用表单提交或者在请求地址中增加请求参数的方式发送请求,Ajax则采用异步方式在后台发送请求。Ajax请求正是通过XMLHttpRequest对象发送的。
3.1 发送简单请求
发送不带任何参数的请求。通常用于自动刷新的应用。
这种情况下操作步骤如下:
第一步,初始化XMLHttpRequest对象;
第二步,打开与服务器的连接,打开连接时,确定发送请求的方法:采用GET或者POST,以及是否采用异步方式。
第三步,设置XMLHttpRequest状态改变时的事件处理函数。
第四步,发送请求,如采用POST方法发送请求,可以发送带参数的请求,GET方式不可以。
看代码3/simple
程序分析:服务器采用的是JSP。Second.jsp。每连接一次服务器端,都要向客户端返回一个字符串,字符串的格式是由3个随机整数通过$连接而成。
客户端first.html。responseText属性里面存储的是服务器端返回的字符串。
split(String str) 把指定的字符串按照$符号进行分离,分离后的结果作为一个字符串数组。
JS中的setTimeout(函数,时间)函数:循环调用一个函数。第二个参数表示时间,单位是毫秒,第一个参数是要循环的函数名。
3.2 发送GET请求
看代码3/GET
本程序是涉及到ajax的技术非常简单。但是其中有几个JS语句需要特别注意,很常用。
解释如下:
option = document.createElement("option");
创建元素(标签),元素名取决于传入的字符串
txtNode = document.createTextNode(cityList[i]);
创建文本节点。文本的内容取决于传入的字符串。这里需要特别注意的是两个标签之间的内容我们认为是一个节点,是文本节点。例如:<abcd>你好啊!</abcd> 其中的“你好啊!”就看作是两个标签元素之间的一个文本节点。
option.appendChild(txtNode);
向标签元素内添加文本节点。
displaySelect. appendChild (option);
根据程序上下文,可以知道displaySelect是一个下拉框的标签元素。appendChild的作用是向下拉框内添加子节点。其中option是要添加的一个opotion子标签。
3.3发送POST请求
POST请求适应性更广,允许发送的参数更多,参数不会被浏览者看到。推荐尽量使用POST而不是GET方法。
发送POST请求的3个步骤:
1 使用open方法打开连接时,指定使用POST方法发送请求。
2 设置正确的请求头,POST请求通常应该设置Content-Type请求头。
3 发送请求,请求参数可以在send方法中确认。
看代码3/POST
程序分析:
发送请求的xmlrequest.open("POST",uri,true);语句后面不再跟参数。参数在xmlrequest.send("id="+id);内完成。另,xmlrequest.setRequestHeader("Content-Type"
,"application/x-www-form-urlencoded");语句不可丢。
注意:如果不带任何参数,send(null)方法不能丢。
3.4发送请求时的编码问题
首先,看代码encoding
该程序得到的结论:
1 尽量不要使用GET方式传递参数给服务器。
2 使用POST方式传递参数的用法。一要注意客户端使用send方法,二要注意服务器端字符集设置采用request.setCharacterEncoding("UTF-8");语句。
3 做到客户端HTML编码与服务器端request.setCharacterEncoding("UTF-8");保持一致。
3.5发送XML请求
对于请求是key-value对的形式传递数据,可以采用POST方式,对于复杂的参数可以考虑使用XML方式传递。
不详细讲解,感兴趣的可以看代码xmlRequest
4、处理服务器响应
4.1 处理的时机
时机:readyState 为4 并且status为200或者304.
4.2使用文本响应
获得服务器响应很简单,通过responseText和responseXML。
responseText:生成普通文本响应。返回服务器响应的字符串。适用于简单的响应。前面例子中已经非常详细的说明用法。不再赘述。
responseXML:生成XML响应。
4.3使用XML响应。
看代码xmlResponse
阅读该代码需要注意的事情
1、 服务器端响应的是完整的XML。
2、 客户端3条核心语句:
var xmldoc = xmlrequest.responseXML;把服务器端响应的全部XML看做一个完整的对象。
var cityList = xmldoc.getElementsByTagName("city");按指定的元素名来获取数组。即:相同元素名的全部元素组成一个数组。
cityList[i].text 获取XML中某个元素内的文本的值用该text属性。
代码ajax.js
/** * @author Lenovo */ // 兼容性创建xmlHttp对象 var snull = "undefined"; var sstr = "string"; // XMLHttpRequest对象 var xhr = null; function createXHR() { // 新浏览器Firefox、Chrome、IE7及以上等 if (typeof XMLHttpRequest != snull) { return new XMLHttpRequest(); } // IE6或者更老的版本 if (typeof ActiveObject != snull) { if (typeof arguments.callee.activeXString != sstr) { var version = [ "MSXML2.XMLHttp6.0","MSXML2.XMLHttp3.0","MSXMLHttp" ]; for ( var i = 0; i < version.length; i++) { try { var xhr = new ActiveXObject(version[i]); arguments.callee.activeXString = version[i]; return xhr; } catch (ex) { throw new Error(ex.toString()); } } return new ActiveXObject(arguments.callee.activeXString); } else { throw new Error("no XHR object available"); } } return null; } function getDataFromServer(url) { // /实例化一个xmlhttp对象 xhr = new createXHR(); // xhr.setRequestHeader("Content-Type",// "application/x-www-form-urlencoded"); if (xhr != null) { xhr.onreadystatechange = handleStateChange; // 创建一个新的http请求,并指定此请求的方法、URL以及验证信息、是否异步(后面代码继续执行,不等待服务器的响应) /* * open(method,url,async,username,password) method 参数是用于请求的 * HTTP方法。值包括 GET、POST 和 HEAD。 url 参数是请求的主体。 大多数浏览器实施了一个同源安全策略,并且要求这个 * URL与包含脚本的文本具有相同的主机名和端口。 async 参数指示请求使用应该异步地执行。 如果这个参数是 * false,请求是同步的,后续对send() 的调用将阻塞,直到响应完全接收。 如果这个参数是 true * 或省略,请求是异步的,且通常需要一个onreadystatechange 事件句柄。 username 和 password * 参数是可选的,为 url所需的授权提供认证资格。 如果指定了,它们会覆盖 url 自己指定的任何资格。 */ xhr.open("post","" + url,true); // 将xhr对象设置请求头信息(向一个打开但未发送的请求设置或添加一个 HTTP 请求。 // 例如:在调用了 open() 之后,但在调用 send() 之前。) /*xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");*/ // 发送请求到http服务器并接收回应 xhr.send("name="+"zhangsan&"+"password="+"psw"); } } function handleStateChange() { // 状态0 -- Uninitialized 初始化状态。XMLHttpRequest 对象已创建或已被 abort() 方法重置。 // 状态1 -- open方法已调用,但是 send() 方法未调用。请求还没有被发送。 // 状态2 -- send方方法已调用,HTTP 请求已发送到 Web 服务器。未接收到响应。 // 状态3 -- 所有响应头部都已经接收到。响应体开始接收但未完成;这时通过responseBody和responseText获取部分数据会出现错误 // 状态4 -- 数据接收完毕,此时可以通过通过responseBody和responseText获取完整的回应数据 // 4 Loaded HTTP 响应已经完全接收。 if (4 == xhr.readyState) { // 返回当前请求的http状态码[200--成功 if ((200 <= xhr.status && 300 > xhr.status) || 304 == xhr.status) { // 处理请求后服务器发回来的数据 dealResponseText(); } else if (404 == xhr.status) { alert("文件不存在!"); } else if (500 == chr.status) { alert("服务器内部错误!"); } else { alert("没有返回正确数据!"); } } else if (3 == xhr.readyState) { // 3 Receiving 所有响应头部都已经接收到。响应体开始接收但未完成。 alert("正在接收数据-3!"); } else if (2 == xhr.readyState) { // 2 Sent Send() 方法已调用,HTTP 请求已发送到 Web 服务器。未接收到响应。 alert("数据已经发送完毕-2!"); } else if (1 == xhr.readyState) { // 1 Open open() 方法已调用,但是 send() 方法未调用。请求还没有被发送。 alert("对象创建完毕,初始化成功-1!"); } else if (0 == xhr.readyState) { // 0 Uninitialized 初始化状态。XMLHttpRequest 对象已创建或已被 abort() 方法重置。 alert("对象已经创建,但还没初始化-0!"); } else { alert("Request was unsuccessful: " + xhr.status+xhr.statusText); } } function dealResponseText() { // responseText 将响应信息作为字符串返回 // alert(xhr.responseText); // responseXML xml的文档节点 // var xmlData = xmlHttp.responseXML; // documentElement 返回跟节点 // var xmlRoot = xmlData.documentElement; // attributes 获取属性集合 // var attrs = xmlRoot.attributes; // alert(attr.length) // ie下获取节点值 text // FF下获取节点值 textContent // 兼容性获取 // var oFind = xmlRoot.getElementsByTagName("findTag")[0]; // var isFindTXT = xmlRoot.text ? oFind.text : oFind.textContent; // alert(isFindTXT); // var jsonTextDiv = document.getElementById("jsonText"); // Deserializes JavaScript Object Notation (JSON) text to // produce a JavaScript value. // // xhr.getResponseHeader('Last-Modified'); // 打印返回来的响应头信息(Server,Content-Length,Date,Last-Modified) document.write(xhr.getAllResponseHeaders() + "<br/>"); // 打印返回来的文本 try{ document.write(xhr.responseText); }catch(ex){ alert("打印返回文本出错!"); } //var data = JSON.parse(xhr.responseText); /* * for ( var i = 0; i < data.length; i++) { var item = date[i]; var div = * window.document.createElement("div"); //div.setAttribute("class",* "dataitem"); // Inserts data into the html. div.innerHTML = item.Name + " * sold "; /*jsonTextDiv*window.document.appendChild(div); } */ //alert(data.length); } function isXML() { }
json.js
/* json.js 2014-02-04 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 code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file adds these methods to JavaScript: object.toJSONString(whitelist) This method 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; }); This file will break programs with improper for..in loops. See http://yuiblog.com/blog/2006/09/26/for-in-intrigue/ This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value,replacer,space) value any JavaScript value,usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted,the text will be packed without extra whitespace. If it is a number,it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or ''),it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found,if the object contains a toJSON method,its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized,or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value,and this will be bound to the object holding the key. For example,this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { 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'; }; You can provide an optional replacer method. It will be passed the key and value of each member,with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined,then the member will be excluded from the serialization. If the replacer parameter is an array of strings,then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations,such as undefined or functions,will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string,then that string will be used for indentation. If the space parameter is a number,then the indentation will be that many spaces. Example: text = JSON.stringify(['e',{pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e',{pluribus: 'unum'}],null,'\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()],function (key,value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text,reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that 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 the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text,value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1],+a[2] - 1,+a[3],+a[4],+a[5],+a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]',value) { var d; if (typeof value === 'string' && value.slice(0,5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5,-1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy,modify,or redistribute. */ /*jslint evil: true,regexp: true,unparam: true */ /*members "","\b","\t","\n","\f","\r","\"",JSON,"\\",apply,call,charCodeAt,getUTCDate,getUTCFullYear,getUTCHours,getUTCMinutes,getUTCMonth,getUTCSeconds,hasOwnProperty,join,lastIndex,length,parse,parseJSON,prototype,push,replace,slice,stringify,test,toJSON,toJSONString,toString,valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx,escapable,gap,indent,Meta,rep; function quote(string) { // If the string contains no control characters,no quote characters,and no // backslash characters,then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable,function (a) { var c = Meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key,holder) { // Produce a string from holder[key]. var i,// The loop counter. k,// The member key. v,// The member value. length,mind = gap,partial,value = holder[key]; // If the value has a toJSON method,call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function,then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder,key,value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null,convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object',we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript,typeof null is 'object',// so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i,value) || 'null'; } // Join all of the elements together,separated with commas,and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array,use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k,value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise,iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value,k)) { v = str(k,value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together,// and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method,give it one. if (typeof JSON.stringify !== 'function') { escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; Meta = { // table of character substitutions '\b': '\\b','\t': '\\t','\n': '\\n','\f': '\\f','\r': '\\r','"' : '\\"','\\': '\\\\' }; JSON.stringify = function (value,space) { // The stringify method takes a value and an optional replacer,and an optional // space parameter,and returns a JSON text. The replacer can be a function // that can replace values,or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number,make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string,it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer,it must be a function or an array. // Otherwise,throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('',{'': value}); }; } // If the JSON object does not yet have a parse method,give it one. if (typeof JSON.parse !== 'function') { cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; JSON.parse = function (text,reviver) { // The parse method takes a text and an optional reviver function,and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder,key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k,v,value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value,k)) { v = walk(value,k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder,value); } // Parsing happens in four stages. In the first stage,we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly,either silently deleting them,or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx,function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage,we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation,and '=' because it can cause mutation. // But just to be safe,we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON 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(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']') .replace(/(?:^|:|,)(?:\s*\[)+/g,''))) { // In the third 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('(' + text + ')'); // In the optional fourth stage,we recursively walk the new structure,passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j},'') : j; } // If the text is not JSON parseable,then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } // Augment the basic prototypes if they have not already been augmented. // These forms are obsolete. It is recommended that JSON.stringify and // JSON.parse be used instead. if (!Object.prototype.toJSONString) { Object.prototype.toJSONString = function (filter) { return JSON.stringify(this,filter); }; Object.prototype.parseJSON = function (filter) { return JSON.parse(this,filter); }; } }());
myajax.html
@H_60_301@<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>我的ajax</title>
<script type="text/javascript" src="js/json.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<input type="button" value="--------------" onclick="getDataFromServer('http://localhost:8080/ajax/ajax')">
</body>
</html>
java servlet AJAX.java
java servlet AJAX.java
package com.trs.action; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Ajax */ // @WebServlet("/Ajax") public class Ajax extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Ajax() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request,HttpServletResponse * response) */ protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { this.doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request,HttpServletResponse * response) */ protected void doPost(HttpServletRequest request,IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String name = request.getParameter("name"); String password = request.getParameter("password"); System.out.println(name+"---"+password); PrintWriter out = response.getWriter(); String str = "[{\"age\":\"40\",\"name\":\"张翠山\",\"sex\":\"男\"}," + "{\"age\":\"109\",\"name\":\"张三丰\",\"sex\":\"男\"}]"; // str="username的密码是password请牢记!!!!"; out.print(str); out.close(); System.out.println("------"); } }
web.xml
@H_60_301@<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>ajax</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ajax</servlet-name>
<servlet-class>com.trs.action.Ajax</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ajax</servlet-name>
<url-pattern>/ajax</url-pattern>
</servlet-mapping>
</web-app>