ajax笔记03 异步同步请求

来源:互联网 发布:sqlserver 查询合计 编辑:程序博客网 时间:2024/05/29 18:27

一,异步,
html代码:回调函数内后加载,实现了异步更新。

<head>    <meta charset="UTF-8" />    <title>Document</title>    <script type="text/javascript">        window.onload=function(){            var btn=document.getElementById('btn');            btn.onclick=function(){                var xhr=null;                if(window.XMLHttpRequest){                    xhr=new XMLHttpRequest();                }else{                    xhr=new AActiveXObject('Microsoft.XMLHTTP');                }                xhr.open('get','page01.php')                xhr.send(null);                xhr.onreadystatechange=function(){                    if(xhr.readyState==4){                        if(xhr.status==200){                            var data=xhr.responseText;                            var obj=JSON.parse(data);/*把data转化成对象*/                            var tag='<div><span>'+obj.info+'</span><span>------</span><span>'+obj.message+'</span></div>';/*把对象解析拼接到页面当中.*/                            var info=document.getElementById('info');/*得到标签*/                            info.innerHTML=tag;/*追加内容到tag中*/                        }                    }                }            }        }    </script></head><body>    <div id="info"> </div>    <input type="button" id="btn" value="点击" /></body></html>

php代码:

 <?php   $arr=array("info"=>"hello","message"=>"hi"); $str=json_encode($arr); echo $str; ?>

二,同步与异步底层原理分析:
Js的事件处理机制:单线程+事件队列
单线程:从上到下。
事件队列中的任务执行的条件:
1,主线程已经空闲
2,任务满足触发条件:
1,定时函数(延时时间已经达到)。
2,事件函数(特定事件被触发)。
3,ajax的回调函数(服务器端有数据响应)

浏览器自身的循环队列, 单线程执行完毕后,查找事件队列中有无可执行的事件(可执行的触发条件),再继续执行。
这里写图片描述