AJAX读取json数据
发布时间:2020-12-16 00:49:08 所属栏目:百科 来源:网络整理
导读:1、创建一个json.txt文件 { "programmers": [ { "firstName": "Brett","lastName":"McLaughlin","email": "brett@newInstance.com" },{ "firstName": "Jason","lastName":"Hunter","email": "jason@servlets.com" },{ "firstName": "Elliotte","lastName":"H
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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |