1 var url = "/data.php"; 2 var param = [ 3 'id=9898', 4 'limit=20' 5 ]; 6 7 var req = new XMLHttpRequest(); 8 9 req.onreadystatechange = function(){10 if(req.readyState == 4){11 var responseHeaders = req.getAllResponseHeaders(); // 获取响应头信息12 var data = req.responseText; // 获取数据13 // 数据处理14 15 }16 };17 18 req.open("GET", url + "?" + param.join("&"), true); // open 三个参数: 请求方式/ url/ 是否异步19 req.setRequestHeader("X-Request-With", "XMLHttpRequest"); // 设置请求头信息20 req.send(null); // 发送一个请求 send() 方法接受一个参数:即作为请求主体发送的数据21 22 23 // 动态脚本注入24 var scriptElement = document.createElement("script");25 scriptElement.src = "http://g.pptv.com/javascript/user.js";26 document.getElementsByTagName("head")[0].appendChild("scriptElement");27 function jsoncallback(jsonString){28 var data = eval('(' + jsonString + ')');29 // 处理数据30 }31 32 // 本地数据存储33 var localCache = {};34 function xhrRequest(url, callback){35 36 // 检查此 URL 的本地缓存37 if(localCache[url]){38 callback.success(localCache[url]);39 return;40 }41 42 // 此 url 对应的缓存没找到,则发送请求43 var req = new XMLHttpRequest();44 req.onerror = function(){45 callback.error();46 };47 48 req.onreadystatechange = function(){49 if(req.readyState == 4){50 if(req.responseText === "" || req.status == "404"){51 callback.error();52 return;53 }54 55 // 存储响应文本到本地缓存56 localCache[url] = req.responseText;57 callback.success(req.responseText);58 }59 };60 61 req.open("GET", url, true);62 req.send(null);63 }