javascript基础 AJAX 第44天

Ajax

XMLHTTPREQUEST 对像

方法主要用来作为发送。


Open(方法,URL)


Send()


setRequestHeader() post发送之前一定要设一项这个值


setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');


属性用来接收数据:


onreadystatechange: 每个状态改变时都会触发这个事件处理器,通常指向一个JavaScript函数;

readyState: 请求的状态。有5个可取值:0=未初始化,1=正在加载,2=已加载,3=交互中,4=完成;

responseText: 服务器的响应,表示为一个串;

responseXML: 服务器的响应,表示为XML。这个对象可以解析为一个DOM对象;

status: 服务器的HTTP状态码(200对应OK404表示Not Found(未找到),等等);

statusText: HTTP状态码的相应文本(OKNot Found等等).


http状态码:

1 系列为消息

2 系列为成功

3 重定向

4 请求错误

5 服务器端错误

注意一些常用的HTTP头信息

Json_encode如果传进内容,必须要为utf8的汉字

ajax.js

ajax=new Object();
//创建ajax对象的方法
ajax.create=function(){
    var request=false;
    if(window.XMLHttpRequest){
        request=new window.XMLHttpRequest;
        //有些浏览器需要设置mime类型,如果存在重写mime类型的属性就进行设置
        if(request.overrideMimeType) {
                request.overrideMimeType('text/xml');
        }
    //针对IE7以下版本解决兼容性问题
    }else if(window.ActiveXObject){
        var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];

        for(i=0;i<versions.length;i++){

            try{
                request=new ActiveXObject(versions[i]);

                if(request){
                    return request;
                }
            }catch(e){
                request=false;
            }
        }
    }
    return request;
}

//创建ajax对象
ajax.request=ajax.create();

ajax.get=function(url,func){
    ajax.request.open('get',url);
    ajax.request.send(null);
    ajax.ready(func);
}
//{username:'liwenkai',password:'cccccc'}
//username=liwenkai&password=ccc
ajax.post=function(url,data,func){

    ajax.request.open('post',url);
    ajax.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    if(typeof(data)=='Object'){
        var str='';
        for(a in data){
            str+=a+'='+data[a]+'&';
        }
        str=str.substr(-1)
    }else{
        str=data;
    }
    ajax.request.send(str);
    ajax.ready(func);
}

ajax.ready=function(func){
    //每次写这么长太烦了,我直接将创建好的对象赋值给变量,直接操作该变量即为操作这个对象实例
    var aj=ajax.request;
    aj.onreadystatechange=function(){
        if(aj.readyState==4){
            if(aj.status==200){
                func(aj.responseText);

            }
        }
    }
}

ajax3.js

//recvType 有两个值HTML 和 XML , 默认为HTML
function Ajax(recvType, bool) {
    var aj = new Object();
    aj.targetUrl = '';    //请求的地址 可以是PHP也可以XML文件
    aj.sendString = '';   //请求服务器传递的字符串  ? & 格式 url 

    if(typeof(bool)=="undefined")
        aj.async=true;
    else
        aj.async=bool;

    aj.recvType=recvType ? recvType.toUpperCase() : 'HTML';//HTML XML
    aj.resultHandle = null;
    aj.ff;
    aj.createXMLHttpRequest = function() {
        var request = false;
        if(window.XMLHttpRequest) {
            aj.ff=true;
            request = new XMLHttpRequest();
            if(request.overrideMimeType) {
                request.overrideMimeType('text/xml');
            }
        } else if(window.ActiveXObject) {
            aj.ff=false;
            var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
            for(var i=0; i<versions.length; i++) {
                try {
                    request = new ActiveXObject(versions[i]);
                    if(request) {
                        return request;
                    }
                } catch(e) {
                    request=false;
                }
            }
        }
        return request;
    }

    aj.XMLHttpRequest = aj.createXMLHttpRequest();

    aj.processHandle = function() {
        if(aj.XMLHttpRequest.readyState == 4) {
            aj.ff=false; //如果是IE7以上则不再执行一次调用
            if(aj.XMLHttpRequest.status == 200) {
                if(aj.recvType == 'HTML') {
                    aj.resultHandle(aj.XMLHttpRequest.responseText);
                }else if(aj.recvType == 'JSON'){
                    aj.resultHandle(eval('('+aj.XMLHttpRequest.responseText+')'));
                }else if(aj.recvType == 'XML') {
                    aj.resultHandle(aj.XMLHttpRequest.responseXML);
                }
            }
        }
    }

    aj.get = function(targetUrl, resultHandle) {
        aj.targetUrl = targetUrl;
        if(resultHandle!=null){
            aj.XMLHttpRequest.onreadystatechange = aj.processHandle;
            aj.resultHandle = resultHandle;
        }
        if(window.XMLHttpRequest) {
            aj.XMLHttpRequest.open('GET', aj.targetUrl, aj.async);
            aj.XMLHttpRequest.send(null);

        } else {
                aj.XMLHttpRequest.open("GET", targetUrl, aj.async);
                aj.XMLHttpRequest.send();
        }
        if(!aj.async && aj.ff)
            aj.processHandle();
    }

    aj.post = function(targetUrl, sendString, resultHandle) {
        aj.targetUrl = targetUrl;

        if(typeof(sendString)=="object"){
            var str="";
            for(var pro in sendString){
                str+=pro+"="+sendString[pro]+"&";
            }

            aj.sendString=str.substr(0, str.length-1);
        }else{
            aj.sendString = sendString;
        }

        if(resultHandle!=null){
            aj.XMLHttpRequest.onreadystatechange = aj.processHandle;
            aj.resultHandle = resultHandle;
        }
        aj.XMLHttpRequest.open('POST', targetUrl, aj.async);
        aj.XMLHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        aj.XMLHttpRequest.send(aj.sendString);
        if(!aj.async && aj.ff)
            aj.processHandle();
    }
    return aj;
}

ajax.html

<script>

    //仅仅是js下面的一对象

    //属性和方法

    //XMLHttpRequest对象

    //总计六个属性,六个方法。还有很多方法和属性不用。

    //php和js 来通信   就用ajax

    //我和谁连接

    var aj=new XMLHttpRequest;
    aj.onreadystatechange=function(){
        if(aj.readyState==4){
            if(aj.status==200){
                alert(aj.responseText);
            }
        }
    }
    aj.open('post','http://127.0.0.1/37/ajax/post.php');
    aj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    aj.send('username=123&password=456');
</script>

fatie.php

<?php

    $conn=new mysqli('localhost','root','php_haha','3mo');

    $conn->set_charset('utf8');

    $sql="select * from x_tie order by id";

    $result=$conn->query($sql);

    if($result&&$conn->affected_rows){

        while($row=$result->fetch_assoc()){
        echo '<div id="result">';

        echo '<li>主题:'.$row['title'].' 内容'.$row['content'].'</li>';

        echo '</div>';
        }

    }

?>

<script src="ajax3.0.js"></script>
<input type="text" name="title" id="title">

<textarea name="content" rows="6" cols="50" onclick="qk(this)" id="content">请输入内容</textarea>

<button onclick="sub()">提交</button>

    <script>
        function qk(obj){
                obj.innerHTML='';

        }

    var t=null;

    var c=null;

    function sub(){
        var title=document.getElementById('title').value;
        var content=document.getElementById('content').innerHTML;
        t=title;
        c=content;
    Ajax().post('write.php','title='+title+'&content='+content,function(data){
            var d=document.getElementById('result');
            d.innerHTML+='<li style="color:red">标题'+t+'    内容'+c+'</li>';
        });
    }
</script>

form.html

<style>
    #tips{width:200px;height:30px;color:red;}

</style>
<form action="reg.php" method="post">
    <input type="text" name="username" onblur="show(this)"><span id="tips"></span>
    <script>
        function show(obj){
            var v=obj.value;
            var aj=new XMLHttpRequest();
        aj.open('get','http://127.0.0.1/37/ajax/reg.php?username='+v+'&rand='+Math.random());
            aj.send(null);
            aj.onreadystatechange=function(){
                if(aj.readyState==4){
                    if(aj.status==200){
                        tt(aj.responseText)
                    }
                }
            }
        }
        function tt(data){
            var tip=document.getElementById('tips');
            tip.innerHTML=data;
        }
    </script>
</form>

reg.php

<?php
$conn=new mysqli('localhost','root','phphaha','3xmo');

$conn->set_charset('utf8');

$username=$_GET['username'];

$sql="select id from 3php_user where username='{$username}'";

$result=$conn->query($sql);

if($result&&$conn->affected_rows){
    echo '用户名不能使用';
}else{
    echo '用户名可以使用';
}
?>

json.html

<html>
    <head>

    </head>

    <body>
        <script src="ajax3.0.js"></script>
        <script>
            Ajax().get('http://127.0.0.1/lamp2/no.44day.js.xmlhttprequest/ajax/json.php',t);

            function t(data){

                var ob=eval('('+data+')');

                document.getElementById('title').innerHTML=ob.title;
                document.getElementById('content').innerHTML=ob.content;
                document.getElementById('status').innerHTML=ob.stats;
            }
        </script>
        <div id="title"></div>
        <div id="content"></div>
        <div id="status"></div>
    </body>
</html>

json.php

<?php
$arr=array('title'=>'标题','content'=>'内容','stats'=>1);
    $t=json_encode($arr);
    echo $t;
?>

page.html

<script src="ajax3.0.js"></script>

<script>
    var d=new Date();

    document.write(d);

</script>

<script>
    imglist('http://127.0.0.1/37/ajax/page.php');
    var u=null;
    function imglist(url){
        if(typeof(da)=='undefined'){
            Ajax().get(url,st);
        }
    }
    function st(data){
         da=new Object();
        da[u]=data;
        document.getElementById('content').innerHTML=data;
    }
</script>
<div id="content"></div>

page.php

<?php
    function __autoload($className){
        include 'page/'.$className.'.class.php';
    }

    $conn=new mysqli('localhost','root','php_haha','php_emo');

    $conn->set_charset('utf8');

    $result=$conn->query('select count(id) from php_user');

    $t=$result->fetch_row();

    $total=$t[0];

    $page=new AjaxPage('page.php?',$total);

    $offset=$page->getOffset();

    $sql="select * from php_ser limit $offset,5";
    $result=$conn->query($sql);
    echo '<table width="800" border="1">';
    while($row=$result->fetch_assoc()){
        echo '<tr>';
        echo '<td>'.$row['id'].'</td>';
        echo '<td>'.$row['username'].'</td>';
        echo '<td>'.$row['password'].'</td>';
        echo '</tr>';
    }
    echo '</table>';
    echo $page->getpage();
?>

page/AjaxPage.class.php

<?php
    class AjaxPage extends Page {
        public function getPage(){
            $pinfo="共 <b>{$this->total}</b> 条记录,本页显示 {$this->start}-{$this->end} 条&nbsp;&nbsp;&nbsp;&nbsp;{$this->page}/{$this->pageNum}&nbsp;&nbsp;&nbsp;&nbsp;";
            if ($this->page==1)
                $pinfo.=$this->first.'&nbsp;&nbsp';
            else
                $pinfo.='<a href="javascript:imglist(\''.$this->url.'page=1\')">'.$this->first.'</a>&nbsp;&nbsp;';

            if ($this->prevPage)
                $pinfo.='<a href="javascript:imglist(\''.$this->url.'page='.$this->prevPage.'\')">'.$this->prev.'</a>&nbsp;&nbsp;';
            else
                $pinfo.=$this->prev.'&nbsp;&nbsp;';

            if ($this->nextPage)
                $pinfo.='<a href="javascript:imglist(\''.$this->url.'page='.$this->nextPage.'\')">'.$this->next.'</a>&nbsp;&nbsp;';
            else
                $pinfo.=$this->next.'&nbsp;&nbsp;';

            if ($this->page==$this->pageNum)
                $pinfo.=$this->last.'&nbsp;&nbsp;';
            else
                $pinfo.='<a href="javascript:imglist(\''.$this->url.'page='.$this->pageNum.'\')">'.$this->last.'</a>&nbsp;&nbsp;';

            return $pinfo;
        }
    }
?>

page/Page.class.php

<?php

    class Page {
        protected $total;     //查询所有的数据总记录数
        protected $page;      //当前第几页
        protected $num;       //每页显示记录的条数
        protected $pageNum;   //一共多少页
        protected $url;
        protected $nextPage;
        protected $prevPage;
        protected $start;
        protected $end;
        protected $first='第一页';
        protected $last='最后一页';
        protected $next='下一页';
        protected $prev='上一页';

        function __construct($url,$total, $num=5) {
            $this->page=isset($_GET["page"])?$_GET["page"]:1;
            $this->url=$url;
            $this->total=$total;
            $this->num=$num;
            $this->pageNum=$this->getPageNum();
            $this->nextPage=$this->getNextPage();
            $this->prevPage=$this->getPrevPage();
            $this->start=$this->getStartNum();
            $this->end=$this->getEndNum();

        }

        protected function getPageNum(){
            return ceil($this->total/$this->num);
        }

        protected function getNextPage() {
            if($this->page==$this->pageNum)
                return false;
            else
                return $this->page+1;
        }   

        protected function getPrevPage() {
            if($this->page==1)
                return false;
            else
                return $this->page-1;
        }
        //数据库查询的偏移量
        public function getOffset() {
            return ($this->page-1)*$this->num;
        }
        //当前页开始的记录数
        protected function getStartNum() {
            if($this->total==0)
                return 0;
            else
                return $this->getOffset()+1;
        }
        //当前页结束的记录数
        protected function getEndNum() {
            return min($this->getOffset()+$this->num,$this->total);
        }

        public function getPage(){
            $pinfo="共 <b>{$this->total}</b> 条记录,本页显示 {$this->start}-{$this->end} 条&nbsp;&nbsp;&nbsp;&nbsp;{$this->page}/{$this->pageNum}&nbsp;&nbsp;&nbsp;&nbsp;";
            if ($this->page==1)
                $pinfo.=$this->first.'&nbsp;&nbsp';
            else
                $pinfo.='<a href="'.$this->url.'page=1">'.$this->first.'</a>&nbsp;&nbsp;';

            if ($this->prevPage)
                $pinfo.='<a href="'.$this->url.'page='.$this->prevPage.'">'.$this->prev.'</a>&nbsp;&nbsp;';
            else
                $pinfo.=$this->prev.'&nbsp;&nbsp;';

            if ($this->nextPage)
                $pinfo.='<a href="'.$this->url.'page='.$this->nextPage.'">'.$this->next.'</a>&nbsp;&nbsp;';
            else
                $pinfo.=$this->next.'&nbsp;&nbsp;';

            if ($this->page==$this->pageNum)
                $pinfo.=$this->last.'&nbsp;&nbsp;';
            else
                $pinfo.='<a href="'.$this->url.'page='.$this->pageNum.'">'.$this->last.'</a>&nbsp;&nbsp;';

            return $pinfo;
        }
    }
?>

reform.html

<style>
    #tips{width:200px;height:30px;color:red;}

</style>
<script src="ajax.js"></script>
<form action="reg.php" method="post">
    <input type="text" name="username" onblur="show(this)"><span id="tips"></span>
    <script>
        function show(obj){
                var v=obj.value;
        ajax.get('http://127.0.0.1/37/ajax/reg.php?username='+v,tt);
        }
        function tt(data){
            var tip=document.getElementById('tips');
            tip.innerHTML=data;
        }
    </script>
</form>