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

【Javascript】原生js实现ajax功能

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