您的位置:首页 > Web前端 > JavaScript

AJAX读取json数据

2013-11-14 15:09 573 查看
转自:http://blog.csdn.net/u011955534/article/details/15942181



1、创建一个json.txt文件

[plain]
view plaincopy

{
"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页面

[html]
view plaincopy

<%@ 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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: