Ajax knowledge points finishing

First, the concept of Ajax

  • Ajax is a technical solution , but not a new technology. It relies on the existing CSS/HTML/Javascript, and the core dependency is the XMLHttpRequest object provided by the browser, which enables the browser to issue HTTP requests and receive HTTP responses.
  • Ajax: Asynchronous JavaScript and XML
    • Asynchronous js: The code of js is executed from the beginning to the end. If a piece of code is not executed, the following code will not be executed. Asynchronous means that ajax can be executed out of order;
    • Ajax can not only process data in XML format, but also process data of json, array, and string type;
    • XML: A format for storing data:
//XML的格式类型;
<name>陈学辉</name>
<age>18</age>
<qq>356985332</qq>
<email>[email protected]</email>
  • What can ajax do:

    A technology for data interaction between js and the backend, by requesting the negotiated interface to obtain the desired data

  • advantage
    When transmitting data, the server will be requested on this page without jumping the page, thereby reducing the pressure on the server. Real-time verification, reducing user rework and optimizing user experience

2. Ajax data interaction process

  • Create an ajax object;
var val=inputs[0].value;
//下面这个是ajax对象;
var ajax=new XMLHttpRequest;
  • Fill in the request address;
//open是ajax对象上的一个方法;

ajax.open("get","php/get.php?user="+val,true);

//第一个参数决定是get还是post方式;
//第二个参数是请求地址,并且把要提交的加上去;
//第三个参数true代表异步,false代表同步;
  • send request;
ajax.send();
  • wait for the server to respond;
ajax.onload=function(){
    //响应好了就接受数据;
    span.innerHTML=ajax.responseText;
}
  • Receive data;

3. The type of data returned

ajax.responseText This is the value returned by the server:
1. It must be a string, some seem to be an object, but it is actually in the form of json;
2. The method of using JSON: JSON.parse(aja.responseText)convert it into a real object and use the method of object operation to operate;

4. XHR compatibility issues

  • XMLHttpRequest is an upgraded version under standard browsers, which are not supported by IE6;
  • ActiveXObject (Microsoft.XMLHTTP) under IE6
//写一个兼容性的函数,实现跨浏览器;
var ajax=null;

if(window.XMLHttpRequest){
    ajax=new XMLHttpRequest;
}else{
    ajax=new ActiveXObject(Microsoft.XMLHTTP)
};

Five, the difference between get and post

  • get method
    • Data transmission is carried out through the information in the address bar, and the size of the transmission is limited;
    • Insecure, all the user's information will be exposed;
    • When splicing data, you need encodeURIto convert the code, otherwise the Chinese will be garbled;

      encodeURIconvert words into symbols;
      decodeURIsymbols into words;

    • No need to set the request header;
    • The data is spliced ​​in the open method;
    • There will be cache problems;
  • post method
    • In theory, there is no length or size limit for transmitting data to the server through send;
    • Relatively safe, because user information is not directly exposed;
    • No transcoding, the data format has been set through the request header, and there will be no garbled characters;
    • The data should be spliced ​​in the send method;
    • no caching issues
    • A request header needs to be set in front of send() (if it is not set, an error will occur);
ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//创建对象;
var ajax=null;
if(window.XMLHttpRequest){
    ajax=new XMLHttpRequest;
}else{
    ajax=new ActiveXObject(Microsoft.XMLHTTP)
};
//填写请求地址;
ajax.open("post","php/post.php",true);
//发送请求,要在send前设置一下请求头;
ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajax.send("user="+val)
//下面的步骤和get方法是一样的;

6. Synchronous and asynchronous

  • Synchronize

    1. When the send()method is called, it will wait for the server to return information. If the server has not responded, the following code will be blocked, and the latter code will not be executed
    . 2. The execution of the latter code is affected by the former code, and the former code did not run through. The code behind will not execute

  • asynchronous
    1. When the send() method is called, the following code will be executed without waiting for the server's response
    2. The execution of the following code is not affected by the previous code

Seven, onreadystatechange and onload

  • ajax.readStateThe running steps of ajax (the first step cannot be captured)
    • If its value is 4, it means that AJAX has finished running;
    • 0 means initialization, the open method has not been called ;
    • 1 means loading, the send method has been called, and the request is being sent;
    • 2 means that the loading is completed, the send method has been completed, and all the response content has been received;
    • 3 means that the response content is being parsed;
    • 4 means the response is complete and can be called on the client side;
  • ajax.status(status code)
    • 200 is a success;
    • 404 is false;
  • onreadStateChange

    readstateThis event is triggered when the value of ;

  • onload
    Triggered after all requests are successfully completed, readstata the is 4
    IE(6,7,8) does not support
    this method. Now this method gradually replaces onreadstatechangethis method
ajax.onreadstatechange=function(){
    if(ajax.readstate==4){          //服务区响应完成了;
        if(ajax.status==200){       //服务器正常;
            //这里放要执行的代码;
        }
    }
}

Eight, package ajax function

Encapsulate the ajax function, and the parameter passed into the function is actually an object ;

  • The package in the object contains the following kinds of data, contained in an object:
    • URL: The address to send the request to, who needs to send the request to;
    • method: the method of sending the request: get or post;
    • dataType: The data type returned after the response: JSON, XML, STRING;
    • data: the data passed at the time of the request (it is an object that needs to be processed);
    • succ: callback after success;
    • fail: callback after failure;
function ajax(json){
    //默认参数;
    var settings={
        url:"",
        method:"get",
        data:{},
        dataType:"json",
        succ:null,
        fail:null
    }

    //用户传的参数覆盖默认参数;
    for (var attr in json){
        settings[attr]=json[attr];
    }

    //把data拼成正确的格式;
    var arr=[];
    for (var attr in settings.data){
        arr.push(attr+"="+settings.data[attr]);
    }
    settings.data=arr.join("&");

    //声明变量;
    var ajax=window.XMLHttpRequest?new XMLHttpRequest():ActiveXObject("Microsoft.XMLHTTP");

    //设置请求方式;
    //请求地址里面的new Date()方法,是为了设置不同的时间戳去解决缓存的问题;
    if(settings.method.toLocalLowCase==="get"){
        ajax.open("get",settings.url+"?"+settings.data+"&"+new Date().getTime(),true);
        ajax.send();
    }else{
        ajax.open("post",settings.url,true);
        //注意要设置一个请求头;
        ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        ajax.send(settings.data);
    }

    //设置完成时间的兼容性;IE6下是没有ajax.onload方法的;
    if(typeof ajax.onload==="undefined"){
        ajax.onreadystatechange=ready;
    }else{
        ajax.onload=ready;
    }

    //封装一个ready()函数;
    function ready(){
        if(ajax.readystate==4){
            if(ajax.status==200){
                //用一个switch判断返回值得类型;
                switch(settings.dataType.toLocalLowCase()){
                    case "string"   : 
                        settings.succ(ajax.responseText);
                        break;
                    case "json"     :
                        //把responsetext转成json格式;
                        setting.succ(JSON.parse(ajax.responseText));
                        break;
                    case "xml"      :
                        settings.succ(ajax.responseXml);
                        break;
                }
            }else{
                settings.fail(ajax.status);
            }
        }
    }
}

It should be noted that JSON.parse on line 57 is incompatible in lower version browsers, you need to download a json2.js file to solve this problem;

Nine, ajax upload

  • Uploading can only be done by the post method, and the background must deal with Chinese-related issues;
  • ajax.upload.onprogress upload progress event; it is what to do when uploading;
    • ev.loadedThe size of the uploaded file;
    • ev.totaltotal file size;

      Through this, an upload progress bar can be made; use this API
      in H5 ;<progress></progress>

  • The list of selected files uploaded by files;

    1. Including file size, type, time of last modification, etc.;
    2. Put it in type="file"the form space;

  • FormData is used to create data in the same format as the form. It is the secondary definition of XHR and is a binary data; lower versions of browsers do not support it ;
    **My own understanding of FormData:
    FormDate can create a new instance, which can inherit the append method on it; this operation is ajax.open placed ajax.send between and **
var formdata=new FormData();

    //下面通过循环把选中的文件里面的额东西添加到这个对象身上;

for(var i=0;i<inputs[0].files.length;i++){

    //inputs[0]指的是一个type="file"的表单控件;

    formdata.append("file",inputs[0].files[i]);
}

    //这时候formdata就可以被发送给服务器了,前面加上一个请求头;

10. Cross-domain issues

  • concept:

    Data under two different domain names interact. The reason why Ajax cannot cross domains is because XMLHttpRequest is restricted by the same- origin policy , so it can only access data under the same origin, but cannot access data under different origins;

  • Same Origin Policy:

    Each website can only read data from the same source, where the same source refers to the combination of hostname ( domain name ), protocol (http/https) and port number . In the case of no explicit authorization, you cannot read and write the resources of the other party. It is the core and most basic security function of the browser;
    as long as there is a difference, it is cross-domain;

  • Ways to solve cross-domain:
    • In standard browsers, XMLHttpRequest cooperates with the backend to set a request permission, and write header('Access-Control-Allow-Origin:*') in php;
    • Server proxy, the disadvantage is that the cost of back-end development is high;
    • iframe、flash、postMessage、WebSocket;

None of these methods are optimal. The following provides a method called jsonp

Eleven, jsonp

  • The concept of jsonp (json+padding)
    • The introduction of some data through the script tag is in synchronous mode. When using the script tag for cross-domain, it is not recommended to load the data in advance, and it needs to be loaded on demand ;
    • When data is required, create a script tag, put the required data in src, monitor whether the request is coming through onload, and call the returned data after the request (asynchronous loading);
    • jsonp cannot use post request, only get request;

      with src attribute

function jsonp(obj){
    var settings={
        url:'',                 //地址
        data:{},                //要发送的数据
        callBack:'callback',    //url里存储回调函数名字的变量
        fnName:'jsonp_'+new Date().getTime(),       //回调函数的名字
        succ:function(){}       //请求成功的回调函数
    };

    for(var attr in obj){
        settings[attr]=obj[attr];
    }

    //创建一个script标签
    var script=document.createElement("script");
    script.className='sc';
    settings.data[settings.callBack]=settings.fnName;

    var head=document.getElementsByTagName('head')[0];


    //把要传的数据拼起来
    var arr=[];         //['wd=sds','cb=jQuery1']
    for(var attr in settings.data){
        arr.push(attr+'='+settings.data[attr]);
    }
    settings.data=arr.join('&');
    script.src=settings.url+'?'+settings.data;

    head.appendChild(script);

    //把回调函数挂载到window身上
    window[settings.fnName]=function(data){
        //当调用这个函数的时候,先把页面中所有的已经请求过的script删掉
        var scripts=head.getElementsByTagName('script');
        for(var i=0;i<scripts.length;i++){
            if(scripts[i].className=='sc'){
                head.removeChild(scripts[i]);
            }
        }

        settings.succ(data);
    };
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324802942&siteId=291194637