ajax

ajax:Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。即用JavaScript异步形式去操作xml。

唯一能做的事就是:数据交互、传输获取数据

优点:节省用户操作、时间,提高用户体验,减少数据请求

请求服务器数据demo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第一个ajax</title>
</head>
<body>
    <input type="button" value="按钮" id="btn" />
</body>
<script>
    var Obtn=document.getElementById('btn');
    Obtn.onclick=function(){
        //打开浏览器
        var xhr=new XMLHttpRequest();// 创建一个ajax对象
        //在地址栏输入地址
        xhr.open('get','1.txt',true);
        //提交
        xhr.send();
        //等待服务器返回内容
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
            alert(xhr.responseText);
            }
        }
    }
</script>
</html>

运行结果:

正确的显示了1.txt中的内容

考虑周全:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第一个ajax</title>
</head>
<body>
    <input type="button" value="按钮" id="btn" />
</body>
<script>
    var Obtn=document.getElementById('btn');

    Obtn.onclick=function(){
        //打开浏览器
        //方法一: var xhr=new XMLHttpRequest();// 创建一个ajax对象
        //方法二:兼容IE6以下
        // var xhr=null;
        // if(window.XMLHttpRequest){
        //     xhr=new XMLHttpRequest();
        // }else{
        //     xhr=new ActiveXObject('Microsoft.XMLHTTP')
        // }
        //方法三:使用try catch
        var xhr=null;
        try{
            xhr=new XMLHttpRequest();
        }catch(e){
            xhr=new ActiveXObject('Microsoft.XMLHTTP')
        }
        //在地址栏输入地址
        xhr.open('get','1.txt',true);//open 方法 参数(打开方式,地址,是否异步)
        //提交
        xhr.send();
        //等待服务器返回内容
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
            alert(xhr.responseText);
            }
        }
    }
    // try{
    //     // alert(a)
    //     throw new Error('错了');
    // }catch(e){
    //     alert(e);
    // }
    // alert('我到这里了')
</script>
</html>
原文地址:https://www.cnblogs.com/pmlyc/p/8578705.html