当前位置:   article > 正文

JavaScript高级程序设计读书笔记(17)——Ajax_javascript高级程序包括ajax

javascript高级程序包括ajax

Ajax

Ajax的作用:通过js代码获取服务器的数据;
Ajax的效果:在不加载整个页面的情况下,通过一个url地址获取到服务器的数据,然后进行页面的局部刷新;
使用步骤:
1、创建XMLHTTPReuest对象;
2、配置对象信息;
3、发送请求;
4、获取服务器端返回的数据。
下面是代码示例:

function myajax(type,URL,params,dataType,callback){
                //1、创建对象和兼容处理
                var xhr=null;
                if(window.XMLHttpRequest){
                    xhr=new XMLHttpRequest();
                }else{
                    //低版本浏览器
                    xhr=new ActiveXObject("Micosoft.XMLHTTP");
                }
             // 2、设置对象
            if(type=="get"){
                URL+="?"+params;
            }
             xhr.open(type,URL,true);
             // 3、发送请求
             if(type=="get"){
                 xhr.send(null);
             }else if(type=="post"){
                 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                 xhr.send(params);
                 // 这里的params表示的是提交的参数
             }
             //4、回调函数,获取服务端返回的数据
             xhr.onreadystatechange=function(){
                 if(xhr.readyState==4){
                     if(xhr.status==200){
                         var result=null;
                         if(dataType=="json"){
                             result=xhr.responseText;
                             // 将JSON数据格式转换成字符串返回给result
                             result.JSON.parse(result);
                         }else if(dataType=="xml"){
                             result=xhr.responseXML;
                         }else{
                             result=xhr.responseText;
                         }
                         callback(result);
                     }
                 }
             }
        }
        window.onload=function(){
            var btn=document.getElementById("btn");
            var username=document.getElementById("username");

            btn.onclick=function(){
                var usernameValue=username.value;
                var type="get";
                var URL="check.php";
                var params="username="+usernameValue;
                var dataType="text";
                myajax(type,URL,params,dataType,function(result){
                    document.getElementById("result").innerText=result;
                });
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/836819
推荐阅读
相关标签
  

闽ICP备14008679号

        
cppcmd=keepalive&