1. 程式人生 > >ajax請求後臺交互json示例

ajax請求後臺交互json示例

words end word 解析 bsp esc head gettime 服務

ajax請求,首先需要服務器(首先你需要node)

npm i -g http-server

技術分享圖片

其次,進入當前目錄(默認服務器端口8080)

技術分享圖片

http-server

點擊進入:localhost:8080/apply-ajax.html

apply-ajax.html

(推薦封裝ajax,以及ajax轉碼過來或者轉碼回去後臺)

 1 <!doctype html>
 2 <html>
 3 
 4 <head>
 5     <meta charset="utf-8">
 6     <
title>Document</title> 7 <meta name="keywords" content=""> 8 <meta name="description" content=""> 9 <style> 10 * { 11 margin: 0; 12 padding: 0; 13 list-style: none; 14 } 15 </style> 16 </head
> 17 18 <body> 19 <button id="btn">請求數據</button> 20 <ul id="list"></ul> 21 <script> 22 var btn = document.getElementById(btn); 23 var list = document.getElementById(list); 24 btn.onclick = function() { 25 //
1.創建XMLHttpRequest對象 26 var xhr = null; 27 if (window.XMLHttpRequest) { // 非IE5/6 28 xhr = new XMLHttpRequest(); //實例對象 29 } else { // IE5/6 30 xhr = new ActiveXObject(Microsoft.XMLHTTP); 31 }; 32 // 2.打開與服務器的鏈接 33 xhr.open(get, test.json?_= + new Date().getTime(), true); //生成不一樣的url解決緩存問題 34 // 3.發送給服務器 35 xhr.send(null); //get請求 36 // 4.響應就緒 37 xhr.onreadystatechange = function() { 38 if (xhr.readyState == 4) { //請求完成 39 if (xhr.status == 200) { //ok 40 var json = JSON.parse(xhr.responseText); //解析成json對象 41 for (var i = 0; i < json.length; i++) { 42 list.innerHTML += <li>姓名: + json[i].name + , 性別: + json[i].sex + , 年齡: + json[i].age + , 成績: + json[i].score + </li>; 43 }; 44 } else { 45 alert(xhr.status); 46 }; 47 }; 48 } 49 } 50 </script> 51 </body> 52 53 </html>

test.json(前臺可以先做json對象數組測試,待數據一到調入接口即可)

1 [
2     { "name": "\u8001\u738b", "sex": "女", "age": 19, "score": 66 },
3     { "name": "老劉", "sex": "男", "age": 22, "score": 72 },
4     { "name": "老李", "sex": "女", "age": 24, "score": 85 },
5     { "name": "老張", "sex": "男", "age": 30, "score": 96 }
6 ]

ajax請求後臺交互json示例