Professional JS(20-JSON Syntax/Serialization/Parse/XMLHttpRequest Object)

1.JSON
①JSON:JavaScript Object Notation對象表示法,一種數據格式。

②JSON syntax allows the representation of three types of values:
a)Simple values—Strings,Numbers,Booleans,and null can all be represented in JSON using the same syntax as JavaScript.The special value undefined is not supported.
b)Objects—The fir st complex data type,objects represent unordered key-value pairs.Each value may be a primitive type or a complex type.
c)Arrays—The second complex data type,array represent on ordered list of values that are accessible via a numeric index.The values may be any type,including simple values,objects and even other arrays.

③There are no variables,functions,or object instances in JSON.JSON is all about representing structured data,and although it shares syntax with JavaScript,it should not be confused with JavaScript paradigms(範疇).

2.Simple Values
*①The big difference between JavaScript strings and JSON strings is that JSON strings must use double quotes(雙引號) to be valid(single quotes causes a syntax error).

3.Objects
+①

//JavaScript中的對象字面量
var Person={
    name:'yyc',
    age:21
};

/*
JSON中的對象---兩者區別
1.只能使用雙引號,不能偷懶用單引號了。
2.屬性也要加雙引號。
3.沒有變量聲明(JSON中沒有變量概念)
4.最後的分號去掉。

*/
{
    "name":"yyc",
    "age":21
}

+②屬性的值可以是簡單值,也可以是複雜類型值,因此可以在對象中嵌入對象。

{
    "name":'yyc',
    "age":21,
    "friend":{
        "name":"asan",
        "address":317
    }
}

4.Arrays
+①

//JS中數組字面量
var values=[403,'hi',false];
//JSON中----無變量---無分號
[403,"hi",false]

+②將數組和對象組合起來,構成更爲複雜的數據集合。

[
    {
        "title":"Professional JavaScript",
        "authors":[
            "Nicholas C. Zakas"
        ],
        "edition":3,
        "year":2011
    },
    {
        "title":"Professional JavaScript",
        "authors":[
            "Nicholas C. Zakas"
        ],
        "edition":2,
        "year":2009
    },
    {
        "title":"Professional JavaScript",
        "authors":[
            "Nicholas C. Zakas"
        ],
        "edition":1,
        "year":2006
    },
    {
        "title":"Professional Ajax",
        "authors":[
            "Nicholas C. Zakas",
            "Jeremy McPeak",
            "Joe Fawcett"
        ],
        "edition":2,
        "year":2008
    },
    {
        "title":"Professional Ajax",
        "authors":[
            "Nicholas C. Zakas",
            "Jeremy McPeak",
            "Joe Fawcett"
        ],
        "edition":1,
        "year":2007
    }
]

5.Parsing and Serialization(解析和序列化)
①JSON’s rise to popularity was not necessarily because it used familiar syntax.More so,is was because the data could be parsed into a usable object in JavaScript.

5.1-JSON對象
①ES5 formalized JSON parsing under a native global called JSON.This object is supported in IE 8+,Firefox 3.5+,Safari 4+,Chrome,and Opera 10.5+.

+②The JSON object has two methods:stringify() and parse().In simple usage,these methods serialize JavaScript objects into a JSON string and parse JSON into a native JavaScript value,respectively.

var book={
    title:"Professional JavaScript",
    authors:[
        "Nicholas C. Zakas"
    ],
    edition:3,
    year:2011
};
/*
1.使用stringify()方法將一個JS對象序列化爲一個JSON字符串。
2.該字符串不包含任何空格字符或縮進。
3.在序列化JS對象時,所有函數及原型成員都會被忽略,包括值爲undefined的任何屬性也會被跳過。
*/
var jsonText=JSON.stringify(book);//{"title":"Professional JavaScript","authors":["Nicholas C. Zakas"],"edition":3,"year":2011}
/*
1.將JSON字符串直接傳遞給JSON.parse()就可以得到相應的JS值。
2.雖然book和bookCopy具有相同的屬性,但它們是兩個獨立的,沒有任何關係的對象。
3.如果傳給parse()方法的字符串不是有效的JSON,則會導致錯誤。
*/
var bookCopy=JSON.parse(jsonText);//{title: "Professional JavaScript", authors: Array(1), edition: 3, year: 2011}

5.2-Serialization Options
①The JSON.stringify() method actually accepts two arguments in addtion to the object to serialize.These arguments allow you to specify alternate ways to serialize a JS object.The first argument is a filter,which can be either an array or a function,and the second argument is an option for indenting(縮進) the resulting JSON string.When used separately or together,this provides some very useful functionality for controlling JSON serialization.

+②If the argument is an array,then JSON.stringify() will include only object properties that are listed in the array.

var book={
    title:"Professional JavaScript",
    authors:[
        "Nicholas C.Zakas"
    ],
    edition:3,
    year:2011
};
//返回的JSON對象:{"title:"Professional JavaScript","edition":3}
var jsonText=JSON.stringify(book,["title","edition"]);

+③When the second argument is a function,the behavior is slightly different.The provided function receives two arguments:the property key name and the property value.You can look at the key to determine what to do with the property.The key is always a string but might be an empty string if value isn’t part of a key-value pair.In order to change the serialization of the object,return the value that should be included for that key.Keep in mind that returning undefined will result in the property being omitted(刪除) from the result.

var book={
    title:"Professional JavaScript",
    authors:[
        "Nicholas C.Zakas"
    ],
    edition:3,
    year:2011
};
var jsonText=JSON.stringify(book,function(key,value){   //replacer替換(過濾)函數
    switch(key){
        case "authors":
            return value.join(",");
        case "year":
            return 2017;
        case "edition":
            return undefined; //屬性property會被省略掉
        default:
            return value;//這裏是保證屬性title的正常返回
    }
});
//實際上,第一次調用這個函數過濾器,傳入的鍵是一個空字符串,而值就是book對象,序列化的JSON字符串爲:
{"title":"Professional JavaScript","authors":"Nicholas C.Zakas","year":2017}

?④Firefox 3.5-3.6 had a bug in its implementation of JSON.stringify() when a function was used as the second argument.The function can act only as a filter:returning undefined means the property is skipped(跳過),while returning anything else causes the property to be included.This behavior was fixed in Firefox 4.

+⑤String Indentation

var book={
    title:"Professional JavaScript",
    authors:[
        "Nicholas C.Zakas"
    ],
    edition:3,
    year:2011
};
var jsonText=JSON.stringify(book,null,4);

/*
{
    "title":"Professional JavaScript",  //每級分別縮進4個空格,順帶換行符。
    "authors":[                         //最大縮進空格數爲10,超過10也當10處理。
        "Nicholas C.Zakas"
    ],
    "edition":3,
    "year":2011
}
*/

//如果縮進參數是一個字符串而非數值
var jsonText=JSON.stringify(book,null,"--");
//縮進字符串最長不能超過10個字符長,否則只顯示前10個字符。
/*
{
--"title":"Professional JavaScript",  //每級分別縮進4個空格,順帶換行符。
--"authors":[                         //最大縮進空格數爲10,超過10也當10處理。
--"Nicholas C.Zakas"
--],
--"edition":3,
--"year":2011
}
*/

+⑥toJSON() method

var book={
    title:"Professional JavaScript",
    authors:[
        "Nicholas C.Zakas"
    ],
    edition:3,
    year:2011,
    toJSON:function(){
        return this.title;
    }
};
var jsonText=JSON.stringify(book);

⑦It’s important to understand the order in which the various parts of a serialization process take place(序列化處理中發生的順序).When an object is passed into JSON.stringify(),the following steps are taken:
1)Called the toJSON() method if it’s available to retrieve the actual value.Use the default serialization otherwise(否則).
2)If the second argument(filter) is provided,apply the filter.The value that is passed into a filter function will be the value returned from step 1.
3)Each value from step 2 is serialized appropriately(對第二步返回的每個值執行相應的序列化).
4)If the third argument(indentation) is provided,format appropriately(執行相應的格式化).

5.3-Parsing Options
+①

var book={
    title:"Professional JavaScript",
    authors:[
        "Nicholas C.Zakas"
    ],
    edition:3,
    year:2011,
    releaseDate : new Date(2017,8,2)  //新增一個releaseDate屬性,該屬性保存着一個Date對象
};
var jsonText=JSON.stringify(book);//序列化
var bookCopy=JSON.parse(jsonText,function(key,value){  //reviver還原函數
    if(key=="releaseDate"){
        return new Date(value);//基於相應的值創建一個新的Date對象
    }else{
        return value;
    }
    /*
    if(key=="releaseDate"){
        return value;
    }
    VM112:16 Uncaught TypeError: Cannot read property 'releaseDate' of undefined
    */
});
alert(bookCopy.releaseDate.getFullYear());//2017

6.Ajax
①Ajax:Asynchronous JavaScript and XML

②Ajax技術的核心是XMLHttpRequest對象(簡稱XHR),爲向服務器發送請求和解析服務器響應提供了流暢的接口。

③使用異步方式從服務器獲得更多信息,使用XHR對象獲得新數據,再通過DOM將新數據插入頁面。因此無需刷新頁面也可從服務器獲得數據,但不一定是XML數據。

7.XMLHttpRequest Object
+①IE 5 was the first browser to introduce the XHR object.It did so through the use of an ActiveX object included as part of the MSXML library.As such,three versions of the XHR object may be in browser:MSXML 2.XMLHttp,MSXML 2.XMLHttp.3.0 and MSXML 2.XMLHttp.6.0.Using an XHR object with the MSXML library requires a function similar to the one used for creating XML documents in Chapter 18.

//function for IE versions prior to 7
function createXHR(){
    if(typeof XMLHttpRequest !="undefined"){
        return new XMLHttpRequest();
    }else if(typeof ActiveXObject != "undefined"){
         if(typeof arguments.callee.activeXString != "string"){
        var versions = ["MSXML 2.XMLHttp.6.0","MSXML 2.XMLHttp.3.0",
                        "MSXML 2.XMLHttp"],
            i,len;
        for(i=0,i=versions.length;i<len;i++){
            try{
                new ActiveXObject(versions[i]);
                arguments.callee.activeXString = versions[i];
                break;
            }catch(ex){
                //skip
            }
        }
    }
      return new ActiveXObject(arguments.callee.activeXString);
    }else{
        throw new Error("No XHR object available");
    }
}

②IE 7,Firefox,Opera,Chrome,and Safari all support a native XHR obejct.

③Since the XHR implementation in each browser is compatible with the original IE version,you can use the created xhr object the same way in all browser.

8.XHR Usage(用法)
①To begin using an XHR object,you will first call the method open(),which accepts three arguments:the type of request to be sent(“get”,”post”,and so on),the URL for the request,and a Boolean value indicating if the request should be sent by asynchronously.

xhr.open("get","example.php",false);

This lines opens a synchronous GET request for example.php.There are a couple of things to note about this code.First,the URL is relative to the page on which the code is called,although an absolute path can be given as well.Second,the call to open() does not actually send the request;it simply perpares a request to be sent.

②You can access only URLs that exist on the same origin,which means the same domain(域),using the same port(端口),and with the same protocol(協議).If the URL specifies any of these differently than the page making the request,a security error is thrown.

+③

var xhr=createXHR();
xhr.open("get","1.txt",true);
xhr.send(null);
if(xhr.status >= 200 && xhr.status < 300 || xhr.status ==304){
    alert(xhr.responseText);
}else{
    alert("Request was unsuccessful: " + xhr.status) ;
}


var xhr=createXHR();
xhr.onreadystatechange=function(){
    if(xhr.readyState==4){
        if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
            alert(xhr.responseText);
        }else{
            alert("Request was unsuccessful: " + xhr.status);
        }
    }
};
xhr.open("get","1.txt",true);
xhr.send(null);

9.Get Requests
①The most common type of request to execute is a GET,which is typically made when the server is being queried for some sort of information.If necessary,query-string arguments can be appended to the end of the URL to pass information to the server.For XHR,this query string must be present and encoded correctly on the URL that is passed into the open() method.

+②One of the most frequent errors made with GET requests is to have an improperly formatted query string.Each-string name and value must be encoded using encodeURIComponent() before being attached to the URL,and all of the name-value pairs must be separated by an ampersand&.

function addURLParam(url,name,value){
    url += (url.indexOf("?")==-1 ? "?" : "&");
    url += encodeURIComponent(name) + "=" +encodeURIComponent(value);
    return url;
}
var url="example.php";
url = addURLParam(url,"name","yyc");
url = addURLParam(url,"book","Professional JS");
xhr.opne("get",url,false);

10.Post Requests
①The second most frequent type of request is POST,which is typically used to send data to the server that should save data.Each POST request is expected to have data submitted(提交) as the body of the request,whereas GET requests traditionally do not.The body of a POST request can contain a very large amount of data,and that data can be in any format.You can initiate a POST request by specifying post at the first argument to the open() method.

+②The second part is to pass some data to the send() method.

function submitData(){
    var xhr = createXHR();
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if((xhr.status >=200 && xhr.status <300) || xhr.status ==304){
                alert(xhr.responseText);
            }esle{
                alert("Request was unsuccessful: " +xhr.status);
            }
        }
    };
    xhr.open("post","postExample.php",false);
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    var form=document.getElementById("user-info");
    xhr.send(serialize(form));
}

③POST requests have more overhead(開銷,消耗的資源) associated with them than do GET requests.In terms of performance(從性能角度來看),GET requests can be up to two times faster than POST requests sending the same amount of data.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章