小试牛刀——AJAX课程

2018-01-22  本文已影响0人  2点半

一.AJAX原理和封装

1.服务器环境的搭建

省略...

2.第一个ajax程序
3.ajax流程对象的创建和兼容
window.onload=function(){
    var oBtn=document.getElementById("btn");
    oBtn.onclick=function(){
        /*1.创建一个ajax对象 ie6一下用的是new AcitveXObject('Mircosoft.XMLHTTP')*/
        var xhr=null
        if(window.XMLHttpRequest){
            xhr=new XMLHttpRequest();
        }else{
            xhr=new ActiveXObject("Microsoft.XMLHTTP")
        }
        /*
            try{
                xhr=new XMLHttpRequest();
            }catch(e){
                xhr=new AcitveXObject("Mirosoft.XMLHTTP")
            }
        */
        /*写入地址*/
        xhr.open("get","1.txt",true);
        /*发送*/
        xhr.send();
        /*监听*/
        xhr.onreadystatechange=function(){
            if(xhr.readyState===4){
                alert(xhr.responseText)
            }
        }

    }
}
4.ajax流程-open方法和表单

表单:数据的提交
action : 数据提交的地址,默认是当前页面
method : 数据提交的方式,默认是get方式
1.get
把数据名称和数据值用=连接,如果有多个的话,那么他会把多个数据组合&进行连接,然后把数据放到url?后面传到指定页面
url长度限制的原因,我们不要通过get方式传递过多的数据
2.post
理论上无限制,
enctype : 提交的数据的格式,默认application/x-www-form-urlencoded

window.onload=function(){
    var oBtn=document.getElementById("btn");
    oBtn.onclick=function(){
        /*1.创建一个ajax对象 ie6以下用的是new AcitveXObject('Mircosoft.XMLHTTP')*/
        var xhr=null
        if(window.XMLHttpRequest){
            xhr=new XMLHttpRequest();
        }else{
            xhr=new ActiveXObject("Microsoft.XMLHTTP")
        }
     
        /*提交请求*/
        /*
        * open方法
        * 参数:
        *       1.打开方式
        *       2.地址
        *       3.是否异步
        *           异步:非阻塞 前面的代码不会影响后面的代码执行
        *           同步:阻塞 前面的代码会影响后面的代码执行 false 一般情况下是不会用同步的直接写在监听里就好了
        * */
        xhr.open("get","1.txt",true);
        /*发送请求*/
        xhr.send();
        /*监听等待服务器返回内容*/
        xhr.onreadystatechange=function(){
            if(xhr.readyState===4){
                alert(xhr.responseText)
            }
        }

    }
}
5.ajax流程-数据的获取
请求状态监控
      /*监听等待服务器返回内容
       * readyState : ajax工作状态
       * responseText : ajax请求的内容就被存放到这个属性下面 类型是字符串类型
       * on readystate change : 当readyState改变的时候触发
       * status : 服务器状态---http状态码
       * */
       xhr.onreadystatechange=function(){
           if(xhr.readyState===4){
               if(xhr.status==200){
                   alert(xhr.responseText)
               }else{
                   alert(xhr.status)
               }
           }
       }
6.应用中get和post的区别处理

get请求

oBtn.onclick=function(){
    var xhr=null
    if(window.XMLHttpRequest){
        xhr=new XMLHttpRequest();
    }else{
        xhr=new ActiveXObject("Microsoft.XMLHTTP")
    }
    /*
    * 1.解决缓存问题 在url?后边连接一个随机数 时间戳
    * 2.乱码,编码encodeURI
    * */
    xhr.open("get",'get.php?username='+encodeURI("名字")+'&age=30&'+new Date().getTime(),true);
    xhr.send();
    xhr.onreadystatechange=function(){
        if(xhr.readyState===4){
            if(xhr.status==200){
                alert(xhr.responseText)
            }else{
                alert(xhr.status)
            }

        }
    }

}

post请求

oBtn.onclick=function(){
    var xhr=null
    if(window.XMLHttpRequest){
        xhr=new XMLHttpRequest();
    }else{
        xhr=new ActiveXObject("Microsoft.XMLHTTP")
    }
    xhr.open("post",'post.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){
            if(xhr.status==200){
                alert(xhr.responseText)
            }else{
                alert(xhr.status)
            }

        }
    }

}
7.ajax获取数据的处理和实例

注:严格的Json的key值一定要用双引号括起来
JSON.stringify() 可以把一个对象转化成对应字符串
JSON.parse() :可以把字符串转成对应对象

实例:ajax的封装及实例

//php:
    header("content-type:text/html;charset='utf-8'");
    error_reporting(0);
  $news=array(
    array('title'=>'法餐烹饪小知识 —— 法式煎蛋','date'=>'2017-1-4'),
    array('title'=>'自抱自泣!早知道我一个人住的小公寓就应该这样装!','date'=>'2017-2-5'),
    array('title'=>'坚持写手账二十一天,我收获了什么','date'=>'2017-3-6'),
    array('title'=>'过日子要有技术含量:这些东西让你的衣食住行更有质量','date'=>'2017-6-6'),
    array('title'=>'开胃易消化、补钙解便秘!宝宝吃惯了粥,换成这个更爱吃!','date'=>'2017-8-25'),
    array('title'=>'大衣指南|跟随时尚的小妖精来学穿大衣','date'=>'2017-9-12'),
    array('title'=>'情人节特辑,淘宝上有哪些值得你收藏的礼物','date'=>'2017-10-22'),
    array('title'=>'治疗失眠症的这4个方法,希望对你有用','date'=>'2017-11-22')
    
  );
  echo JSON_encode($news);
//js:
function ajax(method,url,data,success){
     var xhr=null
        if(window.XMLHttpRequest){
            xhr=new XMLHttpRequest();
        }else{
            xhr=new ActiveXObject("Microsoft.XMLHTTP")
        }
        if(method=='get'&& data){
            url+='?'+data;
        }
         xhr.open(method,url,true);
        if(method=='get'){
            xhr.send();
        }else{
            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(xhr.status)
                }
            }
        }
}
window.onload=function(){
    var oBtn=document.getElementById("btn");
    oBtn.onclick=function(){
       ajax('get','get.php','',function(data){
            var data=JSON.parse(data);
            var oUl=document.getElementById("ul");
            var html="";
            for(var i=0;i<data.length;i++){
                html+='<li><a href="">'+data[i].title+' '+data[i].date+'</a></li>';
            }
            oUl.innerHTML=html;
       });      
     }
}


二.AJAX实例:留言板&瀑布流

瀑布流案例 :

*{margin:0;padding:0;}
#ul{width:1080px;margin:100px auto 0;}
li{width:247px;list-style:none;float:left;margin-right:10px;}
li div{border:1px solid #000;padding:10px;margin-bottom:10px;}
li div img{width:225px;display:block;}

<ul id="ul">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

function ajax(method,url,data,success){
    var xhr=null
    if(window.XMLHttpRequest){
        xhr=new XMLHttpRequest();
    }else{
        xhr=new ActiveXObject("Microsoft.XMLHTTP")
    }
    if(method==='get'&& data){
        url+='?'+data;
    }
    xhr.open(method,url,true);
    if(method==='get'){
        xhr.send();
    }else{
        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(xhr.status)
            }
        }
    }
}

window.onload=function(){
    var oUl=document.getElementById("ul");
    var aLi=oUl.getElementsByTagName("li");
    var iLen=aLi.length;
    var iPage=1;
    var onOff=true;
    getList();
    function getList(){
        ajax('get','getPics.php','cpage='+iPage,function(data){
            var data=JSON.parse(data);
            if(!data.length){//后续没有数据了
                return;
            }
            for(var i=0;i<data.length;i++){
                var _index=getShort();
                var oDiv=document.createElement("div");
                var oImg=document.createElement("img");
                oImg.src=data[i].preview;

                oImg.style.height=data[i].height*(225/data[i].width)+"px";
                oDiv.appendChild(oImg);
                var oP=document.createElement("p");
                oDiv.appendChild(oP);
                aLi[_index].appendChild(oDiv);
            }
            onOff=true;
        })
    }
    window.onscroll=function(){
        var _index=getShort();
        var oLi=aLi[_index];
        var scrollTop=document.documentElement.scrollTop || document.body.scrollTop;
        if(getTop(oLi)+oLi.offsetHeight<(document.documentElement.clientHeight+scrollTop)){
            if(onOff){
                onOff=false;
                iPage++;
                getList();
            }
        }
    }
    function getShort(){
        var index=0;
        var ih=aLi[index].offsetHeight;
        for(var i=0;i<iLen;i++){
            if(aLi[i].offsetHeight<ih){
                index=i;
                ih=aLi[i].offsetHeight;
            }
        }
        return index;
    }
    function getTop(obj){
        var iTop=0;
        while(obj){
            iTop=obj.offsetTop;
            obj=obj.offsetParent;
        }
        return iTop;
    }

}

//php内容
<?php
header('Content-type:text/html; charset="utf-8"');
/*
API:
    getPics.php

        参数
        cpage : 获取数据的页数
*/
$cpage = isset($_GET['cpage']) ? $_GET['cpage'] : 1;

$url = 'http://www.wookmark.com/api/json/popular?page=' . $cpage;

$content = file_get_contents($url);
$content = iconv('gbk', 'utf-8', $content);

echo $content;

?>

三.AJAX跨域解决方案:JSONP

1.问题的回复及跨域限制问题
2.跨域的解决

JSONP: JSON with Padding
1.script标签
2.用script标签加载资源是没有跨域问题的
在资源加载进来之前定义好一个函数,这个函数接收一个参数(数据),函数里面利用这个参数做一些事情
然后需要的时候,通过script标签加载对应远程文件资源,当远程的文件资源被加载进来的时候,就会去执行我们前面定义好的函数,并且把数据当做这个函数的参数传入进去
比如:点击按钮时 创建script 写入地址 append进去

实例:百度下拉实例

<style>
        #q{width:300px;height:30px;padding:5px;border:1px solid #f90;font-size:16px;}
        #ul{border:1px solid #f90;width:310px;margin:0;padding:0;display:none;}
        li a{line-height:30px;padding:5px;text-decoration:none;color:#666;display:block;}
        li:hover{background:#f40;}
</style>
<input type="text" id="q">
<ul id="ul"></ul>

<script>
    function miaov(data){
        var oUl=document.getElementById("ul");
        var html="";
        if(data.s.length){
           for(var i=0;i<data.s.length;i++){
               html+='<li><a target="_blank" href="http://www.baidu.com/s?wd='+data.s[i]+'">'+data.s[i]+'</a></li>'
           }
           oUl.innerHTML=html;
            oUl.style.display='block';
        }else{
            oUl.style.display="none";
        }
    }
    window.onload=function(){
        var oQ=document.getElementById("q");
        var oUl=document.getElementById("ul");
        oQ.onkeyup=function(){
            if(this.value!=""){
                var oScript=document.createElement('script');
                oScript.src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd="+this.value+"&cb=miaov";
                document.body.appendChild(oScript);
            }
        }
    }
</script>
上一篇 下一篇

猜你喜欢

热点阅读