標籤:
該模組主要對url中的query部分進行處理,我們發送GET請求時,將參數直接放在URL中,經常碰到的需求就是把一個對象轉化為query字串放到url中去發送GET請求。io-query模組便提供了兩個方法來處理query:
- objectToQuery將一個object轉化成query字串
- queryToObject將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是一個Null 物件,目的是防止像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 }
dojo/io-query源碼解析