加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

原生AJAX实现的功能代码

发布时间:2020-12-15 20:58:50 所属栏目:百科 来源:网络整理
导读:!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"htmlheadmeta http-equiv="Content-Type" content="text/html; charset=UTF-8"titleInsert title here/titlescript//get 方式实现ajaxvar xhr = new
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script>

	//get 方式实现ajax
	var xhr = new XMLHttpRequest();
	function t1(){

		xhr.open('get','a1.php');

		xhr.onreadystatechange = function (){
			if(xhr.readyState ==4){   //4只能讲明这次交互结束  并不能说明网页正确
			 //== 4 只是说明客户端与服务端的一次交互(请求/回应)完成了.
            // 但并不说明网页本身正确,因为有可能是403,404,500等错误
            // 还得继续判断 http协议返回的状态码
            // 用status属性读取状态码
				if(xhr.status ==200){
					alert(xhr.statusText);
				}
			}
		}

		xhr.send(null);
	}

	//取消请求~~~ 注意var xhr = new XMLHttpRequest();  要为全局变量~
	function t2(){
		xhr.abort();
	}

	//post 的ajax 注意 要xhr.setRequestHeader('content-type','application/x-www-form-urlencoded'); 才可以~!
	function t3(){
		xhr.open('post','a2.php');
		xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
		xhr.send('username=zdhangsan&age=22');

		xhr.onreadystatechange = function(){
			if(xhr.readyState ==4){
				alert(xhr.responseText);
			}
		}

	}


</script>

</head>
<body>

    <input type="button" value="发送请求" onclick="t1();" />
        <input type="button" value="取消请求" onclick="t2();" />
        <input type="button" value="POST数据" onclick="t3();" />
        <input type="button" value="获取头信息" onclick="t4();" />
        <input type="button" value="访问百度" onclick="t5();" />
</body>
</html>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读