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/628 ????????????????xhr = new XMLHttpRequest(); //实例对象29 ????????????} else { // IE5/630 ????????????????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) { //ok40 ????????????????????????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示例
原文地址:https://www.cnblogs.com/cisum/p/8626803.html