Native js calls the json method

Posted by badviking on Wed, 26 Jun 2019 18:43:34 +0200

Ajax Foundation

ajax: no refresh data read, read information on the server

HTTP request method:

GET: Used to get data, such as browsing posts

ajax.judgeXmlHttpRequest('get', 'index.php', function(data){
    alert(data);    //This is the data returned by the server
})

POST: Used to upload data, such as user registration

var dataJson = {
    name: 'ys',age: 123 
}
ajax.judgeXmlHttpRequest('post', 'index.php', function(data){
    alert(data);    //This is the data returned by the server
},dataJson) 

Differences between GET and POST:

GET: Delivered through a web address (put in a url), the data passed will be placed on the web address, name = value &name = value

get mode has small capacity, low security, and cache

POST: Delivered without a web address

post has a large capacity, generally up to 2G, relatively high security, and no cache

Writing native Ajax

Ajax Run Steps

Create an Ajax object

Non-IE6 browsers:

var oAjax=new XMLHttpRequest();

IE6 browser:

var oAjax=new ActiveXObject("Microsoft.XMLHTTP");

Connect to Server

Ajax.open (method, filename, asynchronous transfer);

Block caching method:

Ajax.open('GET','a.txt?t='+new Date().getTime(),true);

Synchronization: js means things must come one by one

Asynchronous: js refers to more than one thing to do together

ajax is transmitted asynchronously, not synchronously

Send Request

Ajax.send();

Receive Return Value

Request status monitoring: onreadystatechange event: Triggered when there is communication between your Ajax and the server, determined primarily by the readyState property that the end is not, that the end does not represent success, and that the status property that determines the end

readyState property: request status

0 (uninitialized) has not yet called the open method

1 (Load) The send() method has been called and the request is being sent

2 (Load Complete) send() method complete, all corresponding content has been received

3 (Resolve) Resolving the content of the response received

4 (Complete) Response content parsing is complete and can be invoked on the client (completion is not necessarily successful, status is required to detect success or failure)

status property:

Request result, success (200) or failure (404):Ajax.status==200

Return value responseText:

Text returned from the server: Ajax.responseText (returned value is a string, sometimes requiring further processing in other formats)

oAjax.onreadystatechange=function(){
    //oAjax.readyState: Indicates the step between the browser and the server
    if(oAjax.readyState==4){  //Read complete
        if(oAjax.status==200){  //Read result is successful
            alert('Success:'+oAjax.responseText);
        }
    }
}

Encapsulate the native Ajax into a function and write the native Ajax as:

The GET method encapsulates the following functions:

function ajax(url,fnSuccess,fnFaild){
    //1. Create an Ajax object.In js, using an undefined variable will cause an error, using an undefined property.Using undefined XMLHttpRequest under IE6 will cause errors, so use it as a property of window
    if (window.XMLHttpRequest) {
        var oAjax=new XMLHttpRequest();//Non-IE6
    }else{
        var oAjax=new ActiveXObject("Microsoft.XMLHTTP");//IE6
    }
    //2. Connect to the server
    oAjax.open('GET',url,true);
    //3. Send Request
    oAjax.send();
    //4. Receive Return Values
    oAjax.onreadystatechange=function(){
        //oAjax.readyState--What step is going on between browser and server
        if(oAjax.readyState==4){  //Read complete
            if(oAjax.status==200){  //Read result is successful
                fnSuccess(oAjax.responseText); //Functions executed on success
          }else{
             if(fnFaild){   //A function to determine whether incoming failures are, that is, whether the user cares about the outcome of the failure
               fnFaild(oAjax.responseText);  //Handle the cause of failure
             }
          }
       }
    }
  }

The POST method encapsulates the following functions:

function ajaxPost(url,id,fnSuccess,fnFaild){
    //1. Create Ajax objects
    if (window.XMLHttpRequest) {
        var xhr=new XMLHttpRequest();//Non-IE6
    }else{
        var xhr=new ActiveXObject("Microsoft.XMLHTTP");//IE6
    }
    //2. Connect to the server
    xhr.open("POST",url,true);
    //Set header information
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    var form=document.getElementById(id);
    //3. Send requests, pass data
    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);
            }
        }
    };
}
Character set encoding: Web pages and requested files should be encoded the same, such as utf8
Cache, prevent caching (frequently changing data, etc., cannot be cached. Mainly used for GET methods), add parameter after path? +'Variable data'can not affect the original data
ajax('a.txt?t='+new Date().getTime(),function(str){
    alert(str);
},function(str){
    alert(str);
});
ajax requests dynamic data, such as json files

1 ajax return value is a string that can be converted by eval to read the returned array/json data

alert(str);
alert(typeof(str));
var arr=eval(str);
alert(typeof(arr));
alert(arr[1]);
alert(arr[1].c);

2 Create elements in conjunction with DOM to display the returned content

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='User name:<span>'+arr[i].user+'</span>Password:<span>'+arr[i].pass+'</span>';
            oUl.appendChild(oLi);
        }
    },function(str){
        alert(str);
    });
} 
Data Type --> The returned data type may be XML (almost obsolete), JSON (now common)

Here's an example of how I recently wrote a native js call json through the get method:

if(!isNaN(matchId)) {
    var xmlHttp = null;
    try {// Chrome, Firefox, Opera, Safari
        xmlHttp = new XMLHttpRequest();
    }catch (e) {
        try {// Internet Explorer IE 6.0+
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {// Internet Explorer IE 5.5+
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("your browser not support ajax!");
            }
        }
    }
    window.onload = function () {
        xmlHttp.open("get",/api/clientMatch/commonMatchDiagram.json?matchId=" + matchId,true);
        xmlHttp.send();
        xmlHttp.onreadystatechange = doResult; //Set Callback Function
    };
    function doResult() {
        var html='';
        if ((xmlHttp.readyState == 4)&&(xmlHttp.status == 200)) {//4 Delegate execution completed, 200 delegate execution succeeded
            var data = JSON.parse(xmlHttp.responseText);
            if(data.code == 200){
            //Code Execution
            }
            document.getElementById('appMatch').innerHTML = html;
        }
    }
}

Topics: JSON PHP IE encoding