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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值