Ajax从某个页面读取数据

本文介绍了一个使用Ajax获取并解析JSON数据的示例,展示了如何通过原生JavaScript实现跨页面的数据请求与处理,具体包括创建XMLHttpRequest对象、设置回调函数及数据解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在某个页面中存储下面的一些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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值