[Summary] AJAX and JSON

AJAX:Asynchronous Javascript And XML”(异步 JavaScript 和 XML)

  • The interactive application development technology
  • Fast dynamic technology web
    Ajax is a without having to reload the entire web page technical section of the page can be updated.
  • However, not a new language, but a combination of several existing technologies of
    advantages:
  • Asynchronous mode to enhance the user experience
  • Optimization of direct transmission of browser and server, reducing unnecessary data back and forth, reducing bandwidth consumption
  • Ajax engine client is running reduces the server load
    Cons:
  • Browser does not support the return key
  • Ajax security issues exposed the details of the interaction with the server
  • Support for the search engines is relatively weak

# How to use Ajax
typically requires the following steps

1, to create XMLHttpRequest object
2, to create a new HTTP request, and the HTTP request specifies the method, the URL
. 3, is provided in response to a change function of the state of the HTTP request


XMLHttpRequest

  • And the server can respond to the request, the user without blocking
  • You can be partial update the page after the page is loaded
    one of the following compatible XMLHttpRequest function to create a package in there:
function  createXHR() {
            if(typeof XMLHttpRequest != "undefined"){
                return new XMLHttpRequest();
            }else if (typeof  ActiveXObject){
                var  xhrArr = ['Microsoft.XMLHTTP','MSXML2.XMLHTTP.6.0','MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP.2.0'];
                var  len = xhrArr.length,xhr;
                for (var i = 0; i < len; i++) {
                    try {
                        xhr = new ActiveXObject(xhrArr[i]);
                        break;
                    }catch (e) {
                        
                    }
                }
                return xhr;
            }else {
                throw new Error('no XHR');
            }
        }
        var  xhr = createXHR();
        console.log(xhr);//输出查看XMLHttpRequest对象

# Create an HTTP request
syntax: open (method, url, async )
create the HTTP request, the request type specified, URL whether asynchronous request processing
parameters:

  • method: the type of request (GET or POST)
    the GET POST faster than, but only with a POST request in the following cases:
    • You can not use the cache file (file or database on the server update)
      + send large amounts of data when (POST does not limit the amount of data)
    • Sends an unknown characters when user's input, POST is more stable and more reliable than the GET
  • url: location of the file on the server
    is the only parameter that must be specified for the file address provided on the server, the file can be any type of file, such as .txt and .xml, the server or the script file, and such .asp .php (before return response, you can perform tasks on the server)
  • async: true (asynchronous) false (synchronous)

open method does not send the request to the real server, which is equivalent to an initialization request and is ready to send can only be used to send URL requests to the same protocol and port of the same domain, or because of security being given the original
create request example:
xhr.open("get","./server/slider.json",true);
Before creating a request You have to respond to the function of the XMLHttpRequest object state changes

xhr.onreadystatechange = function(){  //在onreadystatechange属性发生变化时触发
            if (xhr.readyState ===4){ //0还没初始化 1send已经执行正在发送请求 2send已经执行完毕了 3表示正在解析响应内容 4异步调用成功,响应内容解析完了,可以在客户端调用了
                if((xhr.status >=200 && xhr.status<300) ||xhr.status ===304){
                    //>=200异步调用成功 304表示请求资源没有发生改变,可以直接调用
                }
            }
        }

there's XMLHttpRequest readyState status. Vary from 0-4.
0: Request uninitialized
1: server connection established
2: request received
3: processing request
4: request has been completed, and the response is ready

status represents a stage

  • 200: “OK”

  • 304 represents the requested resource has not changed, you can directly call

  • 404: Page Not Found
    # Send request
    Syntax: send (string)
    sends a request to the server
    parameter: string only for post request
    Note: Only when the POST request parameters can be passed, it does not need to send null, calling the send method after the request is sent to the server
    xhr.send()

  • Create a request using the get method can be used directly behind the URL? Parameters written back pass, more can be separated with &
    # How to add HTTP headers
    to be added, if desired POST HTTP header data as like HTML form, you need to use setRequestHeader (). Then wishes to transmit data in a predetermined send () method

  • 语法:xmlhttp.setRequestHeader(header,value)

  • Use: xmlhttp.setRequestHeader ( "the Content-type '," file application / X-WWW-form-urlencoded ");
    # Set red response function of the state of the HTTP request

  • responseText-- data from a server process returns a string form, eval () can return a string into JavaScript code that can be executed

  • responseXML-- compatible server process returns from the DOM document data objects

  • status-- numeric code returned from the server. The 404 (Not Found)

  • status Text-- accompanying status code string information


#JSON

The JSON ( the JavaScript Object Notation, the JS Object Notation b) is a lightweight data-interchange format. It is based on ECMAScript subset (European Computer Society norms established by js), using completely independent of the programming language of the text format to store and represent data. Simple and clear hierarchy make JSON an ideal data-interchange language. Easy to read and write, but also easy to generate and parse the machine, and effectively improve network transmission efficiency, for tedious substituted bulky XML format.

JSON syntax:
simple values
JSON values can be:
a number (integer or floating point)
string (in double quotes)
a logical value (true or false)
array (in square brackets)
object (braces)
null

  • String must be double quotes , not to use single quotes, and the decimal number must not be used and Infinity NaN
  • It does not support the special value undefined JavaScript in

The object
is a data object as a complex type, a group represented by the ordered pair of keys , each key-value pair may be a simple value, a value may be a complex data type
in JSON object keys must be enclosed in double quotes , because JSON is not the JavaScript statements, there is no end to all the semicolon

  • The same object should not be two of the same name attribute

Array
array is a complex data type, an ordered list of values represents a group which can be accessed by the numerical value of the index

  • Value or after the last member of the object can not comma
    # Method
    two method objects JSON

parse ()
syntax: JSON. parse ()
function: JSON an object character for the conversion of
the stringify ()
Syntax: the JSON.stringify ()
Function: a value into a string in JSON format, can be reduced and the JSON.parse () method

  • JSON is so popular is because you can parse the JSON data structures useful JavaScript objects
  • the stringify JSON object () and parse (), respectively, these two methods may be used to serialize an object JavaScript JSON JSON string and the string parsing JavaScript value on native
  • JavaScript's eval () is similar to .parse () method, can be converted to a string json json object, but eval () to execute code does not meet the JSON format may contain malicious code, not recommended

#jQuery in AJAX
syntax:

.ajax $ ({
. 1 request address
2 request mode
3 data format of
4 synchronous asynchronous
5 successful callback request parameter data to the requesting
})

E.g:

$.ajax({
            url:"./server/slider.json" //请求地址,
            type:"post", //请求方式
            dataType:"json",  //数据格式
            async:true, //同步异步
            success:function(datas){ //请求成功的回调函数 参数为请求到的数据
                renderData(datas.slider);
            }
        })

# Cross-domain
origin policy: domain protocol ports are the same
solution:

  • Cross-Origin Resource Sharing (CORS)
  • Use JSONP
  • Modify document.domain
  • Use window.name

I book Jane Portal: https://www.jianshu.com/p/dd860120d9cf

Guess you like

Origin blog.csdn.net/index1551/article/details/93000492