简单了解AJAX一些写法及注意事项

标题数据提交给服务器有两种方式;

第一种是表单提交,通过表单submit触发,提交到form中action属性地址,使用的方法是method给出的
这种方式有个缺陷,需要跳转页面
第二种是通过ajax提交的,就不能触发submit,而是通过按钮点击,直接使用ajax发送给服务端,发送到的地址就是open中的第二个参数,发送方法就是open的第一个参数,不需要跳转页面,缺陷,部分内容无法进行SEO优化
以上两种情况只能二选一
使用表单提交时,是跳转页面,跳转就不需要考虑回来的问题,所以不牵扯跨域;
但是ajax是访问别的网站并且将数据取回,这就需要考虑跨域问题;

     var xhr=new XMLHttpRequest();
     xhr.addEventListener("load",loadHandler);
     open(method,url,async,userName,password);
     xhr.open("POST","http://localhost:4010/a.php");
     xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
     xhr.send("user=张三");
     function loadHandler(e){
        console.log(this.response);
    }

open(method,url,async,userName,password);
method GET/POST/PUT/DELETE;
GET 通过地址栏后面?带入字符串,字符串格式是变量=值&变量=值的方式传递数据给服务器, 这种方式仅仅去服务端获取,没有单独传递数据,并且从服务端获取需要内容,这个就是GET, 传递给服务器的数据少,而且是明文传递,只能使用字符串,并且数据无法进行多样性嵌套,如果地址是当前页面锚点是可以提交提交页面
POST 数据不是通过地址栏发送,通过数据握手后信道发送数据,并且会将数据转换为二进制数据发送,给服务器,传送数据可以是任意复杂度数据,但是传送的数据类型,包含了字符串,二进制流其他一些格式
PUT DELETE 危险度极高一般不用;
URL 表示发送的地址,如果是GET方式,可以在地址后面增?参数=值传递数据
open的第三个参数是async 异步,默认是true,默认是异步返回数据,如果设置为false,表示同步等待
open的第四个和第五个参数是用户名和密码,有些地址访问是需要用户名和密码
如果直接同post发送给php,php无法接收到数据,设置请求头 如果前端需要通过POST发送数据给php页面,就需要写这个请求头,给nodejs服务发送POST请求时不用写, 这个请求头必须写在open之后,send之前;
xhr.setRequestHeader(“content-type”,“application/x-www-form-urlencoded”)
AJAX不单纯可以请求服务器数据,还可以请求本地数据

     //加载文本文件
     /* var xhr=new XMLHttpRequest();
    xhr.addEventListener("load",loadHandler);
    xhr.open("GET","./a.txt");
    xhr.send();
    function loadHandler(e){
        // console.log(this.response);
        var div=document.querySelector("div");
        div.textContent=this.response;
    } */
    



 //   加载外部的json文件  注意只能读取,不能写入
    /* var xhr=new XMLHttpRequest();
    xhr.addEventListener("load",loadHandler);
    xhr.open("GET","./config.json");
    xhr.send();
    function loadHandler(e){
        var obj=JSON.parse(this.response);
        console.log(obj.backgroundColor);
        document.documentElement.style.backgroundColor=obj.backgroundColor;
       
    } */




// 加载外部XML文件
    // XML 是全语言共通数据
    // 缺陷是数据太大
   /*  var xhr=new XMLHttpRequest();
    xhr.addEventListener("load",loadHandler);
    xhr.open("GET","./a.xml");
    xhr.send();
    function loadHandler(e){
        xml=xhr.responseXML;
        // var num=xml.getElementsByTagName("num")[0].textContent;
        var bn=xml.querySelectorAll("bk>man")[0];
        console.log(bn.getAttribute("name"));
    } */
      


// 加载图片
  /*   var xhr=new XMLHttpRequest();
    xhr.addEventListener("load",loadHandler);
    xhr.open("GET","./img/2-.jpg");
    xhr.send();

    function loadHandler(e){
        console.log(this.response);
    } */


/*      加载html
    var xhr=new XMLHttpRequest();
    xhr.addEventListener("load",loadHandler);
    xhr.open("GET","./a.html");
    xhr.send();
    function loadHandler(e){
        // console.log(this.response);
        var div=document.querySelector("div");
        div.innerHTML=this.response;
    } */

在客户端中可以设置请求头和获取响应头;在服务端中可以获取请求头和设置响应头;
允许请求头数据跨域在PHP中写入
header(“Access-Control-Allow-Origin:");
header("Access-Control-Allow-Headers:
”);

    var xhr=new XMLHttpRequest();
    xhr.addEventListener("load",loadHandler);
    xhr.open("POST","http://localhost:8000");
    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
    // 这个是自定义的请求头,如果跨域时,请求头也必须设置允许跨域才可以发送
    xhr.setRequestHeader("dataType","json");
    // 设置请求头必须写在open和send之间
    xhr.send("user=张三");
    function loadHandler(e){
        // 获取所有响应头消息
        console.log(xhr.getAllResponseHeaders());
        // 获取指定的响应头消息
        console.log(xhr.getResponseHeader("content-type"));
    }
    /*  
    发送JSON字符串
   var obj={
        user:"张三",
        age:30
    }
    var xhr=new XMLHttpRequest();
    xhr.addEventListener("load",loadHandler);
    xhr.open("POST","http://localhost:8000");
    xhr.send(JSON.stringify(obj));

    function loadHandler(e){
       
    } */
    // ________可以上传Blob数据,比如图片文件等
   /*  var form=document.querySelector("form");
    form.addEventListener("submit",submitHandler);

    function submitHandler(e){
        e.preventDefault();
        var file=document.querySelector("[type=file]");
        console.log(file.files);
        // 上传文件
        var xhr=new XMLHttpRequest();
        xhr.open("POST","http://localhost:8000");
        xhr.addEventListener("load",loadHandler);
        xhr.send(file.files[0]);
        var xhr=new XMLHttpRequest();
        xhr.open("POST","http://localhost:8000");
        xhr.addEventListener("load",loadHandler);
        xhr.send(file.files[1]);
        var xhr=new XMLHttpRequest();
        xhr.open("POST","http://localhost:8000");
        xhr.addEventListener("load",loadHandler);
        xhr.send(file.files[2]);
    }

    function loadHandler(e){
        console.log(this.response);
    } */
    // -------直接发送document或者可以直接将HTML发送给服务器
    // 也可以将DOMString发送给服务器
    /* var x=new XMLHttpRequest();
    x.addEventListener("load",xmlLoadHandler);
    x.open("GET","./a.xml");
    x.send();

    function xmlLoadHandler(){
        // console.log(x.responseXML)
        var xhr=new XMLHttpRequest();
        xhr.addEventListener("load",loadHandler);
        xhr.open("POST","http://localhost:8000");
        xhr.send(x.responseXML);

    }
    function loadHandler(){
        
    } */



    // ------formData 发送表单数据
   /*  var form=document.querySelector("form");
    form.addEventListener("submit",submitHandler);

    function submitHandler(e){
        e.preventDefault();
        var fd=new FormData(form);
        // for(var values of fd){
        //     console.log(values);
        // }
        var xhr=new XMLHttpRequest();
        xhr.addEventListener("load",loadHandler);
        xhr.open("POST","http://localhost:8000");
        // 将这个表单数据提交
        xhr.send(fd);
    }

    function loadHandler(e){

    } */
    // _________________timeout  超时   因为各种因素导致数据前后端传递的延迟
    // 设置超时等待,如果超过超过这个时间,就切断数据发送
 /* 
    var xhr=new XMLHttpRequest();
    xhr.open("POST","http://localhost:8000");
    xhr.addEventListener("load",loadHandler);
    // 超时事件,如果触发超时等待就会执行这个事件
    xhr.addEventListener("timeout",timeOutHandler)
    xhr.timeout=2000;//设置超时等待2秒
    xhr.send("aaa");


    function loadHandler(){

    }

    function timeOutHandler(e){
        xhr.abort();//将原来的链接断掉
        // 重新再创建并执行新的xhr的通信
    }

*/

     // __________readystate

  // load事件以后再使用就是加载本地数据时使用
   /*  var xhr=new XMLHttpRequest();
    // 在整个AJAX的通信中属于全过程监听,当状态改变时,触发该函数
    xhr.addEventListener("readystatechange",readyStateHandler);
    xhr.open("POST","http://localhost:8000");
    xhr.send("aaa");


    function readyStateHandler(e){
        console.log(this.readyState,this.status);
        if(this.readyState===4 && this.status===200){
            console.log(this.response);
        }
    } */

//promise封装ajax;
    function ajax(data){
        return new Promise(function(resolve,reject){
            var xhr=new XMLHttpRequest();
            xhr.onreadystatechange=function(){
                if(xhr.readyState===4){
                    if(xhr.status===200){
                        resolve(xhr.response);
                    }else{
                        reject(xhr.status);
                    }
                }
            }
            xhr.onerror=function(){
                reject(xhr.status);
            }
            xhr.open("POST","http://localhost:8000");
            xhr.send(JSON.stringify(data));
        })
    }


    ajax({name:"xietian",age:30}).then(function(res){
        console.log(res);
    }).catch(function(err){
        console.log(err);
    })
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值