Ajax从某个页面读取数据

前端之家收集整理的这篇文章主要介绍了Ajax从某个页面读取数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在某个页面中存储下面的一些json数据:

{  
"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" }  
]  
}  

利用原生Ajax发送请求获取上个页面中的数据,并写入本页面中:
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>  
<head>
  <Meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>People at Clearleft</title>
<script type="text/javascript">
var httpRequest;
//创建异步请求
function creatXMLHttpRequest(){
	if(window.XMLHttpRequest){
		httpRequest= new XMLHttpRequest();
	}
	else{
		if(window.ActiveXObject){
			try{
				httpRequest = new ActiveXObject("Msxm12.XMLHTTP");
			}catch(e){
				try {
					httpRequest= new ActiveXObject("Microsoft.XMLHTTP");
				}catch(e){}
			}
		}
		
	}
	
}
//ajax 回调函数
function callback(){
	if (httpRequest.readyState==4){
		if(httpRequest.status==200){
			
			/*主要操作*/
			var xmldata=httpRequest.responseText;	
			/*将数据转为json格式*/
			var json = eval("("+xmldata+")");
                         /*给页面中的文本框内容赋值*/
                        document.getElementById("i").value=json.programmers[0].firstName; 
			//document.getElementById("str").innerHTML=json;
		   
			//document.getElementById("str").innerHTML=xmldata;
		  			
		}
	}
	
}
function  getdata(){
	creatXMLHttpRequest();
	httpRequest.onreadystatechange=callback;
	httpRequest.open("GET","json.txt",true);
	httpRequest.send(null);		
}


</script>
</head>

<body>
<div id="str" style="display:none"></div>
<input id="i" type="text" value="">
<input type="button" value="find data" onclick="getdata()"/>
</body>

</html>

猜你在找的Ajax相关文章