zoukankan      html  css  js  c++  java
  • Ajax初体验

    Ajax步骤:

    1.创建一个对象XMLHttpRequest对象.

    2.设置回调onreadystatechange方法.判断成功与否( status=200 readyStates = 4).

    题外话:

    staus各数值所代表的意思:
    200=成功;
    404:路径请求错误;
    503:服务不可用;
    readyStates各数值所代表的意思:
    0 (未初始化):(XMLHttpRequest)对象已经创建,但还没有调用open()方法。
    1 (载入):已经调用open() 方法,但尚未发送请求。
    2 (载入完成): 请求已经发送完成。
    3 (交互):可以接收到部分响应数据。
    4 (完成):已经接收到了全部数据,并且连接已经关闭。

    3.设置open
      第一个参数 GET或者POST
      第二个参数 Url
      第三个参数 true(异步) false(同步);

    4.发送请求send方法 GET形式send方法没有参数;

    POST请求 需要设置hdader
    setRequestHeader("Content-Type","application/x-www-form-urlencoded");

    Javascript原生写法:

    GET方法:
      function ajax(url,fnSuccess,fnFaild){
        //1.创建Ajax对象
        //js中,使用一个没有定义的变量会报错,使用一个没有定义的属性,是undefined
        //IE6下使用没有定义的XMLHttpRequest会报错,所以当做window的一个属性使用
        if (window.XMLHttpRequest) {
          //非IE6
          var oAjax=new XMLHttpRequest();
        }else{
          //IE6
          var oAjax=new ActiveXObject("Microsoft.XMLHTTP");
        }
        //2.连接到服务器
        oAjax.open('GET',url,true);
    
        //3.发送请求
        oAjax.send();
    
         //4.接收返回值
       oAjax.onreadystatechange=function(){
          //oAjax.readyState--浏览器和服务器之间进行到哪一步了
          if(oAjax.readyState==4){  //读取完成
            if(oAjax.status==200){  //读取的结果是成功
                fnSuccess(oAjax.responseText); //成功时执行的函数
              }else{
                 if(fnFaild){   //判断是否传入失败是的函数,即用户是否关心失败时的结果
                   fnFaild(oAjax.responseText);  //对失败的原因做出处理
                 }
              }
           }
        }
      }
    
    POST方法:
      function ajaxPost(url,id,fnSuccess,fnFaild){
        //1.创建Ajax对象
        if (window.XMLHttpRequest) {
          //非IE6
          var xhr=new XMLHttpRequest();
        }else{
          //IE6
          var xhr=new ActiveXObject("Microsoft.XMLHTTP");
        }
        //2.连接到服务器
        xhr.open("POST",url,true);
        //设置头信息
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        var form=document.getElementById(id);
        //3.发送请求,传递数据
        xhr.send(serialize(form));
        xhr.onreadystatechange=function(){
          if(xhr.readyState==4){
            if ((xhr.status>=200 && xhr.status<300) || xhr.status==304) {
              fnSuccess(xhr.responseText);
            }else{
              fnFaild(xhr.responseText);
            }
          }
        };
      }
    
    注**
    1--字符集编码:网页和被请求的文件的编码要相同,如都是utf8
    2--缓存,阻止缓存(经常改变的数据等,不能够缓存.主要用于GET方法)
      --传参时在路径后面加?+'可变的数据' 可以不影响原数据
        ajax('a.txt?t='+new Date().getTime(),function(str){
          alert(str);
        },function(str){
          alert(str);
        });
    
    3--ajax请求动态数据:如json文件
        3.1--ajax返回值是一个字符串,可通过eval转换后来读取返回的数组/json数据
            alert(str);
            alert(typeof(str));
            var arr=eval(str);
            alert(typeof(arr));
            alert(arr[1]);
            alert(arr[1].c);
    
        3.2--结合DOM创建元素,来显示返回的内容
          oBtn.onclick=function(){
            ajax('data/arr3.txt?t='+new Date().getTime(),function(str){
              var arr=eval(str);
              for (var i = 0; i < arr.length; i++) {
                var oLi=document.createElement('li');
                oLi.innerHTML='用户名:<span>'+arr[i].user+'</span>密码:<span>'+arr[i].pass+'</span>';
                oUl.appendChild(oLi);
              }
            },function(str){
              alert(str);
            });
          }

     jQuery写法:

    $.ajax({
        url:'/comm/test1.php',
        type:'POST', //GET
        async:true,    //或false,是否异步
        data:{
            name:'yang',age:25
        },
        timeout:5000,    //超时时间
        dataType:'json',    //返回的数据格式:json/xml/html/script/jsonp/text
        beforeSend:function(xhr){
            console.log(xhr)
            console.log('发送前')
        },
        success:function(data,textStatus,jqXHR){
            console.log(data)
            console.log(textStatus)
            console.log(jqXHR)
        },
        error:function(xhr,textStatus){
            console.log('错误')
            console.log(xhr)
            console.log(textStatus)
        },
        complete:function(){
            console.log('结束')
        }
    })
    慢慢的努力的成为一个好的前端.
  • 相关阅读:
    1113 Integer Set Partition
    1114 Family Property
    1115 Counting Nodes in a BST
    1116 Come on! Let's C
    Maven 常用命令
    Maven 快照
    Maven 插件
    Maven POM
    Maven 中央仓库
    Maven 依赖机制
  • 原文地址:https://www.cnblogs.com/xpcool/p/7553089.html
Copyright © 2011-2022 走看看