js深入JS笔记

JS深入(Ajax)

2017-09-15  本文已影响0人  余生筑

Ajax的完整请求过程

1. 创建Ajax对象

2.连接到服务器

3.发送请求

4.接收返回值

read.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <input type="button"  id="btn" value="读取">
    <script>
        var obtn=document.getElementById("btn")

        //创建Ajax对象
        obtn.onclick=function(){
            var oAjax=new XMLHttpRequest()

        //连接服务器
        oAjax.open('GET','a.txt?t='+new Date().getTime(),true)//+new Date().getTime()用于保证a.text实时更新。true表示"异步传输"

        //发送请求
        oAjax.send()

        //接收返回
        oAjax.onreadystatechange=function(){
        if(oAjax.readyState==4){ //响应内容解析完毕
        if(oAjax.status==200){//解析成功
            alert(oAjax.responseText)
        }  
        else{
            alrt('s')
        }
    }
}
}
</script>
</body>
</html>

a.txt

abcsdfgh
上一篇 下一篇

猜你喜欢

热点阅读