JavaScript Basics (2): JSON and Ajax

One: JSON Basics

1. What is JSON?
JSON (JavaScript Object Noataion) is a subset of the js language. It is a data format. Using JSON, you can easily serialize the properties of a js object into a string or deserialize a JSON string into a js object. Compared with the traditional XML data transmission format, JSON is easier to read and understand, and it is also easier to parse JSON strings (one line of code). Compared with XML, the same information is transmitted, but JSON strings are smaller in size.

// 一个JSON字符串例子
{
    "firstName": "Cruise",
    "lastName": "Tom",
    "age": 56,
    "address": null
}

2. Data format in JSON JSON can represent three kinds of data: simple values
, objects and arrays 2.2 Objects:

// JSON表示的对象中只有属性,没有变量、函数和方法,属性名称必须使用双引号!
{
    "firstName": "Cruise",
    "lastName": "Tom",
    "age": 56,
    "address": {
        "street": "123 someplace",
        "city": "Los Angeles",
        "state": "California"
    }

}

2.3 Arrays (multiple objects):

[
    {
        "firstName": "Sheldon",
        "lastName": "Cooper",
        "age": 37,
        "address": {
            "street": "321 someplace",
            "city": "Pasadena",
            "state": "California"
        }

    },
    {
        "firstName": "Cruise",
        "lastName": "Tom",
        "age": 56,
        "address": {
            "street": "123 someplace",
            "city": "Los Angeles",
            "state": "California"
        }
    }
]

3. Serialization and deserialization of JSON strings

    // 创建一个js对象
    var person = {
        "firstName": "Sheldon",
        "lastName": "Cooper",
        "age": 37,
        "address": {
            "street": "321 someplace",
            "city": "Pasadena",
            "state": "California"
        }
    };

    // 将js对象序列化一个JSON字符串
    var json = JSON.stringify(person);

    // 将JSON字符串反序列化为js对象
    var actor = JSON.parse(json);

Two: Ajax basics

1. The concept of
Ajax Ajax allows the browser to send requests to the server and receive data through javascript without refreshing the entire web page.

2. XMLHttpRequest object The
XMLHttpRequest object is a built-in object of the browser, which can be used to send requests to the server and obtain data.
2.1 Create an XMLHttpRequest object for connecting to the server, sending requests and receiving data

var request = new XMLHttpRequest();

2.2 Initialize the XMLHttpRequest object

// 初始化XMLHttpRequest对象
// requestType: 请求类型,POST/GET
// url: 请求发送的目标
// async: 指定请求是同步还是异步模式,默认是异步的(默认值true),一般省略该参数
request.open(requestType, url, async);

2.3 Asynchronous call, bound event handler
The XMLHttpRequest object contains a readyState property whose value is a number to indicate the status of the request:

0---对象已创定,未调用open()方法
1--已调用open()初始化对象,未发送请求
2--请求已发送
3--开始接收来自服务器的数据
4--服务器响应完毕(200/404/500...)

When the value of the readyState property changes, the readystatechange event will be triggered, and the onreadystatechange event handler will be called.

// 定义事件处理函数,XMLHttpRequest请求完毕的调用
function reqReadyStateChange(){
    if(request.readyState == 4){    // 服务器响应完毕
        if(request.status == 200){  // http状态码200,请求处理成功
            // responseText表示服务器响应的数据
            alert(request.responseText);
        } else {
            alert("The server retutn a status code of " + request.status);
        }
    }
}

// 将函数绑定到事件上
request.onreadystatechange = reqReadyStateChange;

// 发送请求,接收一个字符串类型的参数,参数为发送给服务器的请求体,如果不包含请求体,则将null作为值传入(必须)
request.send(null);

2. Encapsulate simple Ajax modules
Encapsulate Ajax modules to improve code reusability

// 封装XMLHttpRequest对象的函数,GET类型的异步Ajax请求
function HttpRequest(url, callback){
    // 创建并初始化XMLHttpRequest对象
    this.reqeust = new XMLHttpRequest();
    this.reqeust.open("GET", url, true);

    var temRequest = this.reqeust;

    // 定义事件处理函数
    function reqReadyStateChange(){
        if(temRequest.readyState == 4){     // 服务器请求响应完毕
            if(temRequest.status == 200){   // 请求处理成功
                // responseText属性为服务器返回的数据
                callback(temRequest.responseText);
            }
        }
    }

    // 为readystatechange事件绑定事件处理函数
    temRequest.onreadystatechange = reqReadyStateChange;
}

// 封装send方法,之后调用send()方法无需传递参数
HttpRequest.prototype.send = function(){
    this.reqeust.send(null);
}

Guess you like

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