前端之家收集整理的这篇文章主要介绍了
AJAX读取json数据,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
1、创建一个json.txt文件
{
"programmers": [
{ "firstName": "Brett","lastName":"McLaughlin","email": "brett@newInstance.com" },{ "firstName": "Jason","lastName":"Hunter","email": "jason@servlets.com" },{ "firstName": "Elliotte","lastName":"Harold","email": "elharo@macfaq.com" }
],"authors": [
{ "firstName": "Isaac","lastName": "Asimov","genre": "science fiction" },{ "firstName": "Tad","lastName": "Williams","genre": "fantasy" },{ "firstName": "Frank","lastName": "Peretti","genre": "christian fiction" }
],"musicians": [
{ "firstName": "Eric","lastName": "Clapton","instrument": "guitar" },{ "firstName": "Sergei","lastName": "Rachmaninoff","instrument": "piano" }
]
}
2、jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
var xmlHttp=null;
//创建xmlhttprequest对象
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveObject("Microsoft.XMLHTTP");
}
function myclick(){
try{
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.open("get","json.txt",true);
xmlHttp.send();
}
catch(exception){
alert("xmlHttp fail");
}
}
function handleStateChange(){
if(xmlHttp.readyState==4 && xmlHttp.status==200){
var result=xmlHttp.responseText;
var json=eval("("+result+")");
alert(json.programmers[0].firstName);
}
}
</script>
</head>
<body>
<div>
<input type="button" value="AjaxTest" onclick="myclick()"/>
</div>
</body>
</html>