计算机网络/计算机科学与应用/系统/运维/开发

一篇文章搞定ajax

ajax 四部曲:

  1. 创建ajax对象

  2. 连接服务器

  3. 发送请求

  4. 接收返回值


实例一:

<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="button" value="测试" id="btn1">
<script>
window.onload = function(){
var oBtn = document.getElementById("btn1");
oBtn.onclick=function(){
//步骤1.创建ajax对象
//主流浏览器
//var  xhr = new XMLHttpRequest();
//ie6以下浏览器
//var  xhr = new ActiveXObject("Microsoft.XMLHTTP");
        //处理兼容
        //如果XMLHttpRequest存在 那么就是主流浏览器 否则就是ie6浏览器
        
        if (window.XMLHttpRequest) {
        //创建ajax对象
        var  xhr = new XMLHttpRequest();
        }else{
        //IE6创建ajax对象
        var  xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        //步骤2:打开服务器
        /*
          open(提交方法[post/get],url,是否异步[true/false])
          异步:多件事情一起做
          同步:多件事情一件一件做
         */
        //new Date().getTime() 表示清除缓存
        var url = "ajax1.txt?t="+new Date().getTime();
        xhr.open("get",url,true);
        //步骤3 发送请求
        xhr.send();
        //步骤4 接受返回
        xhr.onreadystatechange = function(){
        /*
        xhr.readyState  表示服务器执行到哪种状态
        0 未初始化 还没有调用open()
        1  载入 表示已经调用open 正在发送请求
        2  载入完成  send()方法执行完毕 已收到全部响应内容
        3  解析  正在解析响应内容
        4  完成  响应内容完毕 可以调用
         */
        if(xhr.readyState==4){
        if(xhr.status==200){
        alert("正在读取文件:"+xhr.responseText);
        }else{
        alert("异常");
        }
        }
        }
}
}
//js 变量和属性
//声明变量及输出
//var  a = 12;
//alert(a);
//window对象的a属性
//alert(window.a);
//如果直接输出a 会报错
//alert(a);//Uncaught ReferenceError: a is not defined
//不会报错  undefined
//alert(window.a);
//加上window只是找不到window的属性a
</script>
</body>
</html>


实例二:

<body>
	<input type="button" value="按钮" id="btn">
	<script>
	var oBtn = document.getElementById('btn');
	oBtn.onclick=function(){
		//打开浏览器
		var xhr = null;
		try{
			xhr = new XMLHttpRequest();
		}catch(e){
			xhr=new ActiveXObject("Microsoft.XMLHTTP");
		}
		//在地址栏输入地址
		/*
		 1.缓存  在url?后面连接一个随机数 时间戳
		 2. 乱码  编码encodeURI
		 */
		xhr.open('get','ajax2.php?username='+encodeURI('刘伟')+'&age=30&'+new Date().getTime(),true);
		//提交
		xhr.send();
		//等待服务器返回内容
		/*
			readyState: ajax工作状态
			responseText: ajax 请求返回的内容就被存放到这个属性下面
			onreadystatechange : 当readyState改变时候触发
			status: 服务器状态, http状态码
		 */
		xhr.onreadystatechange=function(){
			if(xhr.readyState==4){
				alert(xhr.responseText);
			}
		}
	}
	</script>
</body>

实例三:get方式提交


<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
表单: 数据提交
action: 数据提交的地址 默认是当前页面
method: 数据提交方式
       1. get
        把数据名称和数据值用=连接,如果有多个的话 那么它会把
        多个数据组合用&进行连接,然后把数据放到url?后面进行传递到指定页面
        ajax2.php?uername=zs&age=12
       2. post
enctype:提交的数据格式
application/x-www-form-urlencoded
<form action="ajax2.php" method="get">
姓名<input type="text" name="username" />
年龄<input type="text" name="age" />
<input type="submit" value="提交" />
</form>
</body>
</html>
<script>
var oBtn = document.getElementById('btn');
oBtn.onclick=function(){
//打开浏览器
var xhr = null;
try{
xhr = new XMLHttpRequest();
}catch(e){
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
//在地址栏输入地址
/*
 1.缓存  在url?后面连接一个随机数 时间戳
 2. 乱码  编码encodeURI
 */
xhr.open('get','ajax2.php?username='+encodeURI('刘伟')+'&age=30&'+new Date().getTime(),true);
//提交
xhr.send();
//等待服务器返回内容
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
alert(xhr.responseText);
}
}
}
</script>


实例四:post方式提交

<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
表单: 数据提交
action: 数据提交的地址 默认是当前页面
method: 数据提交方式
       1. get
        把数据名称和数据值用=连接,如果有多个的话 那么它会把
        多个数据组合用&进行连接,然后把数据放到url?后面进行传递到指定页面
        ajax2.php?uername=zs&age=12
        url 长度限制原因 ,我们不要通过get方式传递过多的数据
       2. post
         理论上无限制
enctype:提交的数据格式
application/x-www-form-urlencoded
<form action="ajax3.php" method="post">
姓名<input type="text" name="username" />
年龄<input type="text" name="age" />
<input type="submit" value="提交" />
</form>
</body>
</html>
<script>
var oBtn = document.getElementById('btn');
oBtn.onclick=function(){
//打开浏览器
var xhr = null;
try{
xhr = new XMLHttpRequest();
}catch(e){
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
//在地址栏输入地址
xhr.open('post','ajax3.php',true);
//提交
//post 方式  数据放在send()里面作为参数传递
//声明发送的数据类型
//post 没有缓存问题
//无需编码
    xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
xhr.send('username=leo&age=30');
//等待服务器返回内容
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
alert(xhr.responseText);
}
}
}
</script>
<script>
var oBtn = document.getElementById('btn');
oBtn.onclick=function(){
//打开浏览器
var xhr = null;
try{
xhr = new XMLHttpRequest();
}catch(e){
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
//在地址栏输入地址
xhr.open('post','gteList.php',true);
//提交
    xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
xhr.send('username=leo&age=30');
//等待服务器返回内容
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if (xhr.status==200) {
alert(xhr.responseText);
}else{
alert('出错了,Err:'+xhr.status);
}
}
}
}
</script>

实例五:综合实例

getList2.php
<?php 
header('Content-type:text/html;charset=utf-8');
$arr1 = array(
array('title'=>'江苏渔民打捞上缴9个可疑水下装置 18人获国家重奖','data'=>'2018.1'),
array('title'=>'蒙冤男子4年花光160万赔偿金:无法理解这个时代','data'=>'2018.2'),
array('title'=>'"加拿大鹅"北京店开业:排队要30分钟','data'=>'2018.3'),
array('title'=>'嫦娥四号实施变轨控制','data'=>'2018.4'),
array('title'=>'谁给权健式保健品把把脉?','data'=>'2018.4'),
array('title'=>'谁给权健式保健品把把脉?','data'=>'2018.4'),
array('title'=>'谁给权健式保健品把把脉?','data'=>'2018.4'),
);
echo json_encode($arr1);
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="button" value="按钮" id="btn">
<ul id="ul1"></ul>
<script>
var oBtn = document.getElementById('btn');
oBtn.onclick=function(){
//打开浏览器
var xhr = null;
try{
xhr = new XMLHttpRequest();
}catch(e){
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
//在地址栏输入地址
xhr.open('post','gteList2.php',true);
//提交
    xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
xhr.send();
//等待服务器返回内容
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if (xhr.status==200) {
//alert(xhr.responseText);
var data = JSON.parse( xhr.responseText );
var oUl=document.getElementById('ul1');
var html='';
for (var i = 0;i<data.length; i++) {
html+='<li><a href="">'+data[i].title+'</a><span>'+data[i].data+'</span></li>';
}
oUl.innerHTML=html;
}else{
alert('出错了,Err:'+xhr.status);
}
}
}
}
</script>
</body>
</html>

实例6:封装ajax

ajax.js
 function ajax(method,url,data,success){
  //打开浏览器
var xhr = null;
try{
xhr = new XMLHttpRequest();
}catch(e){
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
if(method == 'get' && data){
url+='?'+data;
}
//在地址栏输入地址
xhr.open(method,url,true);
//提交
    if(method=='get' && data){
    xhr.send();
    }else{
    //post发送
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
xhr.send(data);
    }
//等待服务器返回内容
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if (xhr.status==200) {
success && success(xhr.responseText);
}else{
alert('出错了,Err:'+xhr.status);
}
}
}
  }
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="button" value="按钮" id="btn">
<ul id="ul1"></ul>
<script src="ajax.js"></script>
<script>
var oBtn = document.getElementById('btn');
oBtn.onclick=function(){
ajax('get','gteList2.php','',function(data){
var data = JSON.parse( data );
var oUl=document.getElementById('ul1');
var html='';
for (var i = 0;i<data.length; i++) {
html+='<li><a href="">'+data[i].title+'</a><span>'+data[i].data+'</span></li>';
}
oUl.innerHTML=html;
});
setInterval(function(){
ajax('get','gteList2.php','',function(data){
var data = JSON.parse( data );
var oUl=document.getElementById('ul1');
var html='';
for (var i = 0;i<data.length; i++) {
html+='<li><a href="">'+data[i].title+'</a><span>'+data[i].data+'</span></li>';
}
oUl.innerHTML=html;
});
},1000);
}
</script>
</body>
</html>


ajax

泰山崩于前而色不变,麋鹿兴于左而目不瞬,然后可以制利害,可以待敌。--心术

评论

^