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 }