ajax(一)——基础知识

<!DOCTYPE html>
<html>
  <head>
    <title>ajax.html</title>
	
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
	<script type="text/javascript">
	
		window.οnlοad=init;
		function init() {
			var btn=document.getElementById("getData");
			btn.οnclick=getData;
		}
		//总的思路就是这样 页面一些事件比如点击等来触发ajax ajax去后台请求数据 这时前台没有任何变化好刷新 然后返回结果 通过dom节点绘制页面 只是局部刷新
		function getData() {
			//1.创建XMLHttpRequest对象
			//2.检测XMLHttpRequest对象的状态,在合适的时候处理
			//3.发送请求
			var xhr=createXmlHttpRequest();	//不同浏览器有兼容问题
			xhr.open("GET","ajax",true);
			xhr.onreadystatechange=function(){
				alert(xhr.readyState);
				if(xhr.readyState==4&&xhr.status==200){
					//xhr.responseText获取文本 包括HTML
					//xhr.responseXML获取xml对象 传过来的是xml字符串 前台可以解析
					alert(xhr.responseText);
					document.getElementById("serverData").innerHTML=xhr.responseText;
					//可以通过xml来传递数据 但是很浪费 现在常用json在前后台传递数据
				}
			};
			//可以传入参数,post请求时有效, get请求的参数直接在请求地址中传入
			xhr.send();
			//json就是js的对象格式 如果传回来的是字符串可以用eval来解析
			
			var json=[
				{id:21},
				{id:12}
			];
			alert(json);
			json="[{id:21},{id:12}]";
			alert(json);
			json=eval(json);
			alert(json);
			
		}
		function createXmlHttpRequest() {
			if(window.ActiveXObject){
				//针对IE5和IE6
				return new ActiveXObject("Microsoft.XMLHTTP");
			}else if(window.XMLHttpRequest){
				//针对其他主流浏览器
				return new XMLHttpRequest();
			}else{
				alert("使用的浏览器不支持ajax");
				return null;
			}
			
		}
	</script>
  </head>
  
  <body>
    <input type="button" value="getData" id="getData" />
    <div id="serverData"></div>
  </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值