ajax数据格式JS
Posted Flamel
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax数据格式JS相关的知识,希望对你有一定的参考价值。
index2.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> window.onload = function(){ var anodes = document.getElementsByTagName("a"); for(var i = 0; i<anodes.length; i++){ anodes[i].onclick = function(){ var request = new XMLHttpRequest(); var method = "GET"; var url = this.href; request.open(method,url); request.send(null); request.onreadystatechange = function(){ if(request.readyState == 4){ if(request.status == 200||request.status == 304){ //1.结果为json格式,所以需要使用responseText来获取 var result = request.responseText; //使用eval方法把字符串转化为本地 的JS代码执行 var object = eval("("+ result +")"); //结果不能直接用,必须先创建对应的节点,再把节点加到#details去; var name = object.person.name; var website = object.person.website; var email = object.person.email; //alert(name); //alert(website); //alert(email); var anode = document.createElement("a"); anode.appendChild(document.createTextNode(name)); anode.href = "taobao" + email; var h2node = document.createElement("h2"); h2node.appendChild(anode); var anode2 = document.createElement("a"); anode2.appendChild(document.createTextNode(website)); anode2.href = "taobao" + website; var detailnode = document.getElementById("details"); detailnode.innerHTML=""; detailnode.appendChild(h2node); detailnode.appendChild(anode2); } } } return false; } } } </script> </head> <body> <ul> <li><a href="file/1.js"> 购物网站 </a></li> <li><a href="file/2.js"> 学习网站 </a></li> </ul> <div id="details"> </div> </body> </html>
1.js
/**
* 会报错,但是无关紧要。
*/
{"person":{
"name":"taobao",
"website":"https://www.taobao.com/",
"email":"https://www.tmall.com/"
}
}
2.js
/**
*
*/
{"person":{
"name":"xuexi",
"website":"https://www.w3school.com.cn/",
"email":"https://www.runoob.com/"
}
}
结果截图:
以上是关于ajax数据格式JS的主要内容,如果未能解决你的问题,请参考以下文章
怎么用jsp生成json格式数据,然后用js又怎样读取其数据?