JavaScript JSON 与 AJAX

JavaScript JSON 与 AJAX

JSON is a lightweight data-interchange format, and with the completion of AJAX messaging service distal end, JSON paper describes the use of native AJAX writing, packaging solutions, and cross-domain JSONP JSONP utility functions and AJAX

JSON concept

  1. All programming languages ​​are inseparable from the three data structures

    scalar scalar: numeric and string

    sequence sequence: arrays and lists

    mapping mapping: value pairs

  2. JSON: JavaScript Object Notation, a lightweight data-interchange format

  3. JSON data is not normal object method, or an array of such objects comprising

    var person = {
        "name": "jett",
        "age": "22",
        "sex": "男"
    }
    var persons = [
        {
        "name": "jett",
        "age": "22",
        "sex": "男"
    	},
        {
        "name": "lily",
        "age": "20",
        "sex": "女"
    	}
    ]
    

The basic format of JSON

  1. Key-value pairs are separated by colons
  2. Key names forced to use double quotes
  3. Parallel data separated by commas
  4. Parallel data sets by []enclosing

And convert JSON object

  1. JSON an object is converted into JS

    JSON.parse()

    <div id='box' data-info='{"name":"Jett","age":"22"}'></div>
    
    // JSON.parse(str) str -> object
    var box = document.getElementById('box');
    var jsonData = box.getAttribute('data-info');
    var obj = JSON.parse(jsonData);
    console.log(obj);
    // {name:"Jett",age:"22"}
    

    eval()

    var obj = eval('('+jsonData+')');
    // eval 可以执行任何 JS 代码,所以可以将 jsonData 当作代码执行
    // 为安全性考虑,最好使用 JSON.parse()
    
  2. JS objects into JSON

    JSON.stringify()

    var obj = {
            name: 'Jett',
            age: 22,
            sex: '男'
        }
    var jsonData  = JSON.stringify(obj);
    console.log(jsonData);
    // {"name":"Jett","age":22,"sex":"男"}
    

The concept of AJAX

  1. AJAX: Asynchronous JavaScript and XML, Asynchronous JavaScript and XML

  2. AJAX is not a new programming language, but a new way to use existing standards

  3. The biggest advantage is AJAX without reloading the entire page, you can exchange data with the server and update parts of the page content

  4. AJAX works

    Browser to create XMLHttpRequest object, send AJAX request

    Server receives the request, create a response, return data

    Browser receives the data, dynamic rendering pages

The basic wording of AJAX

  1. Create XMLHttpRequest object

    XMLHttpRequest for exchanging data with the server in the background

    Compatible with IE7 and above

    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        // 兼容 IE6/5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
  2. AJAX request transmission

    GET request

    url request address, the address used in the ?spliced message content, such as? name = Jett & age = 22

    xmlhttp.open('GET',url, true);
    xmlhttp.send();
    

    POST request

    Method send incoming message contents, such as: name = Jett & age = 22

    xmlhttp.open('POST',url, true);
    // xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    // 通过 setRequestHeader 设置请求头
    xmlhttp.send(data);
    

    GET request faster, but less secure than the POST, and the transmission data size is limited

    The third parameter represents the true asynchronous, synchronous behalf fasle

  3. Listener response status

    XMLHttpRequest object has readystatechange event for changing the listening readystate

    readystate XMLHttpRequest object shows a state AJAX request

    0: 请求未初始化
    1: 服务器连接已建立
    2: 请求已接收
    3: 请求处理中
    4: 请求已完成,且响应已就绪
    

    status XMLHttpRequest object http request with a status code

    200: 请求
    404: 未找到页面
    

    Readystatachange monitor events and determine the state

    When xmlhttp.readyState to 4, xmlhttp.status 200, representing a request success response and ready

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            // ...
        }
    }
    
  4. Treatment response

    ResponseXML responseText XMLHttpRequest object or attribute for receiving data returned from the server

    As the name suggests, respnseXML for receiving the response data in XML format, responseText for receiving general data

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            console.log(xmlhttp.responseText);
            // 获得响应数据并使用
        }
    }
    

JSONP concept

  1. Cross-domain requests

    URL = protocol name + host name and port number + Resource Name

    Domain = protocol name + host name and port number

    For security reasons, only when the destination address and the domain of the page request in the same domain are allowed access

  2. JSONP is a cross-domain solution

    Current methods to solve the problem of cross-domain browser has JSONP, cors strategy, cors strategy is a new feature of HTML5, older browsers may not support, JSONP is the most common treatment

JSONP principle

  1. In a number of HTML tags, some labels have cross-domain functionality, such as script, img, iframe

  2. Is the ability to cross-area JSONP script tag dynamically generates a script tag for the request address specified src

    The method defined in page

    <scrip type="text/javascript">
        funtion test(data) {
        	console.log(data);
        }
    </scrip>
    <!--动态生成的 script 标签-->
    <script type="text/javascript" src="htpp://localhost:8888"></script>
    

    htpp: // localhost: 8888 Address data returned

    test('这是请求返回的数据')
    

    The resulting script tag is added to the DOM, the browser according to the src request destination address, the returned data obtained as a script tag, the browser will return as a data code to perform JS, is to perform the method defined in the page, just where the parameters can be successfully brought to a page

  3. We define a function on the page, its function name via the URL query string passed to the server, the server stitching string, the function returns the JS code execution, and data on the parameters to be passed, so that on the page defined functions to be executed, and received data from the server, the successful implementation of the callback function, you can process the data of the server

JSONP callback function

  1. For ordinary AJAX request we can readystatechange event listener XMLHttpRequest, the judge readystate and status requests and responses to its completion, in order to perform a successful callback or callback error

  2. Essentially JSONP src script tag is to utilize the request, the response follows:

  • If there is a resource src point, and which is returned as a string of successful execution of the JS code

    I.e., the function defined within the page is successfully performed, the successful callback function within the data may be processed to get the parameters

  • If src points less than the purpose of resource access

    script tag will trigger error events, listen to this event will be the opportunity to perform error correction

    var script = document.createElement('script');
    script.onerror = funtion() {
        // 执行出错回调函数
    }
    
  • If there is a resource pointing to src, the string will be returned because it is the script tag is executed, the implementation process mistakes

    Before executing a successful callback function, add a script tag attribute to label an object, whether the load while monitoring script event object has the label attribute

    Because onload function is executed after the script tag loaded, the code execution script tag after its introduction, will respond onload handler, determining whether to add a successful tag attributes, tag can be introduced into the script code is its successful execution, if the flag attribute is undefined, the execution error callback

    var script = document.createElement('script');
    window.callback = function (res) {
        script['jsonp'] = 1;
        // 执行成功回调函数
    }
    script.onload = function () {
        if (typeof script['jsonp'] === 'undefined') {
            // 执行出错回调函数
        }
    }
    
  1. Note that, IE8 and below the script tag object does not support onerror, does not support onload, but support onreadystatechange

    By determining readystate to its loaded state script tag when readystate is loaded or Complete, represents the script tag loaded, i.e., the code script tag is introduced has been performed, the same, add tag attributes as script objects before successful callback function, by determining whether the attribute flag added successfully to be incorporated in its script tag codes executed successfully, if the tag attribute is undefined, an error correction is performed

    script.onreadystatechange = function () {
        // 正则表达式判断 readystate 是否为 loaded 或 complete
        if (/loaded|complete/i.test(this.readyState)) {
            if (typeof script['jsonp'] === 'undefined') {
                // 执行出错回调函数
            }
        }
    }}
    
  2. Dynamically generated function name, with the use of onload onreadystate determining the load state, corresponding to the delete function is finished, the script tag and remove the corresponding node

    JSONP function in their own package, we may add the function as the dynamic callback objects in the window, src specified resource script such as the callback return type ( 'Data') of the string data, can perform this function directly and obtain data, but when we JSONP function optimization, will want to delete function dynamically created, property will be reported in IE8 does not support the delete window, we can add functions on Window.prototype, can also be directly executed, and delete support

AJAX package with JSONP

  1. Ajax a function package, supports get, post, jsonp three forms of request, parameters passed as objects

  2. Configuration Item

    var opt = {
        type: 'get', 
    	url: 'http://...',
    	data: { // 数据使用对象形式
          name: 'zzh',
          age: '21'
        },
    	async: true, // 默认 true
    	success: function(res) {
            
        },
    	error: function() {
            
        },
    	timeout: 3000 // 默认 60000
    }
    
  3. Code

    function ajax(option) {
        // 设置默认参数
        var opt = {
            type: option.type.toUpperCase(),
            url: option.url,
            data: option.data || null,
            async: option.async || false,
            success: option.success,
            error: option.error,
            timeout: option.timeout || 60000
        };
        // 用于 jsonp 的回调函数名
        var callback = 'callback' + new Date().getTime();
    
        var type = opt.type,
            success = opt.success,
            error = opt.error,
            data = parseData(opt.data); // 将 data 对象装换成查询字符串
    
        if (type === 'GET' || type === 'POST') {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    success && success(xhr.responseText, xhr.status);
                } else {
                    error && error(xhr.status);
                }
            }
            if (type == 'GET') {
                opt.url += data;
                data = null;
            }
            xhr.open(type, opt.url, opt.async);
            xhr.send(data);
            setTimeout(function () {
                xhr.abort();
                console.error(opt.url + '请求超时');
            }, opt.timeout);
        } else if (type === 'JSONP') {
            var script = document.createElement('script');
            script.src = opt.url + data;
            // 选则存放在 Window 原型上,window 下可以使用
            // 如果直接存放在 window 上,IE8 window 属性不支持 dalete
            Window.prototype[callback] = function (res) {
                script['jsonp'] = 1;
                success && success(res);
            }
            document.body.appendChild(script);
    
            // -[1,] 在 IE8 返回 NaN,IE9 及以上返回 -1
            if (-[1,]) {
                // IE9 及以上支持 onerror
                // onerror 用于请求失败,未执行 callback
                // onload 用于请求成功,但执行 callback 出错
                script.onerror = script.onload = function () {
                    if (typeof script['jsonp'] === 'undefined') {
                        error && error();
                    }
                    script.parentNode.removeChild(script);
                    delete  Window.prototype[callback];
                }
            } else {
                // script.onreadystatechange 兼容 IE8
                script.onreadystatechange = function () {
                    // -[1,] 在 IE8 返回 NaN,IE9 及以上返回 -1
                    if (/loaded|complete/i.test(this.readyState)) {
                        if (typeof script['jsonp'] === 'undefined') {
                            error && error();
                        }
                        script.parentNode.removeChild(script);
                        delete  Window.prototype[callback];
                    }
                }
            }
    
        }
    
        function parseData(data) {
            var arr = [],
                str;
            if (type === 'GET') {
                str = '?';
            } else if (type === 'POST') {
                str = '';
            } else if (type === 'JSONP') {
                str = '?callback=' + callback + '&';
            }
            for (var k in data) {
                arr.push(k + '=' + data[k]);
            }
            return str + arr.join('&');
        }
    }
    // 使用示例
    ajax({
        type: 'jsonp',
        url: 'http://127.0.0.1:8888/',
        data: {
            name: 'jett',
            age: 22
        },
        success: function (res) {
            console.log('接收数据:' + res);
        },
        error: function () {
            console.log('error() 执行了');
        }
    })
    

Guess you like

Origin www.cnblogs.com/pgjett/p/12630265.html