【Javascript】原生js实现ajax功能

本文介绍了一种通过JavaScript实现的Ajax GET请求方法,可用于从服务器异步获取数据并更新到网页上,无需刷新整个页面。文章详细展示了如何创建XmlHttpRequest对象,并通过onreadystatechange事件处理返回的数据。

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<link rel="icon" href="https://i.alipayobjects.com/common/favicon/favicon.ico" type="image/x-icon"> 
<script type="text/javascript">
//创建XmlHttpRequest对象
function CreateXmlHttpRequest(){
	var xmlHttp = null;
	try{
		//code for IE7+, Firefox, Opera, Chrome,Safari
		xmlHttp = new XMLHttpRequest();
	}catch(e){
		//IE
		try{
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{
				//code for IE6, IE5
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){
				alert("Your Browser does not support ajax");
			}
		}
	}
	return xmlHttp;
}
//实现GET功能
function AjaxGet(url){
	var xmlHttp = CreateXmlHttpRequest();
		
	if(xmlHttp==null){
		alert("获取XmlHttpRequest失败");
	}	
	
	xmlHttp.onreadystatechange = function(){
		//查看状态码请点击下面链接
		//    http://www.w3school.com.cn/ajax/ajax_xmlhttprequest_onreadystatechange.asp
		//其中,xmlHttp.status为0表示url为本地资源		
		if(xmlHttp.readyState == 4 && (xmlHttp.status == 200 || xmlHttp.status==0)){
			document.getElementById("text1").value = xmlHttp.responseText;
		}
	}
	
	xmlHttp.open("GET",url,true);
	xmlHttp.send();
}

</script> 
</head>
<body>
<input id="button1" type="button" value="get text" onclick="return AjaxGet('1.txt');"/>
<input id="text1" type="text" />
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值