该模块主要对url中的query部分进行处理,我们发送GET请求时,将参数直接放在URL中,经常碰到的需求就是把一个对象转化为query字符串放到url中去发送GET请求。io-query模块便提供了两个方法来处理query:
从对象转化成query是拼接的过程,对象的字段和值都需要编码
objectToQuery: function objectToQuery(/*Object*/ map){ // summary: // takes a name/value mapping object and returns a string representing // a URL-encoded version of that object. // example: // this object: // // | { // | blah: "blah", // | multi: [ // | "thud", // | "thonk" // | ] // | }; // // yields the following query string: // // | "blah=blah&multi=thud&multi=thonk" var enc = encodeURIComponent, pairs = []; for(var name in map){ var value = map[name]; // backstop是一个空对象,目的是防止像toString这种继承来的字段被处理 if(value != backstop[name]){ var assign = enc(name) + "="; if(lang.isArray(value)){ //数组的话对每一个数组元素都编码成:multi=thud&multi=thonk for(var i = 0, l = value.length; i < l; ++i){ pairs.push(assign + enc(value[i])); } }else{ pairs.push(assign + enc(value)); } } } return pairs.join("&"); // String }
query到对象是字符串分割的过程,参数和参数值都需要使用decodeURIComponent来解码
queryToObject: function queryToObject(/*String*/ str){ // summary: // Create an object representing a de-serialized query section of a // URL. Query keys with multiple values are returned in an array. // // example: // This string: // // | "foo=bar&foo=baz&thinger=%20spaces%20=blah&zonk=blarg&" // // results in this object structure: // // | { // | foo: [ "bar", "baz" ], // | thinger: " spaces =blah", // | zonk: "blarg" // | } // // Note that spaces and other urlencoded entities are correctly // handled. // 字符串分割 var dec = decodeURIComponent, qp = str.split("&"), ret = {}, name, val; for(var i = 0, l = qp.length, item; i < l; ++i){ item = qp[i]; if(item.length){ var s = item.indexOf("="); if(s < 0){// 空值 name = dec(item); val = ""; }else{ // 分割"a=b"的形式,name为a,val为b name = dec(item.slice(0, s)); val = dec(item.slice(s + 1)); } //一个name对应多个value则转化为数组 if(typeof ret[name] == "string"){ // inline'd type check ret[name] = [ret[name]]; } if(lang.isArray(ret[name])){ ret[name].push(val); }else{ ret[name] = val; } } } return ret; // Object }