如何以更好的方式编写此查询字符串?

时间:2011-11-23 08:34:42

标签: javascript refactoring query-string

我在JavaScript中看到了一行代码库来构造查询字符串:

    var queryParameters = "imagePath=" + encodeURIComponent(_image.source) + "&saveMode=" + saveMode + "&pageFolderId=" + pageFolderId + "&id=" + pageId + "&parent=" + parent;
    queryParameters += "&quality=" + sQuality.value + "&commands=" + commandQueue.Serialize();

有更好的方式来写这个吗?

4 个答案:

答案 0 :(得分:4)

如果您使用的是jQuery,则只需使用表示查询字符串选项的对象:

var queryParameters = jQuery.param({
    imagePath: _image.source,
    saveMode: saveMode,
    pageFolderId: pageId,
    // ...
});

jQuery会自动对查询字符串值进行编码,因此您无需在encodeURIComponent上调用_image.source。有关详细信息,请参阅:http://api.jquery.com/jQuery.param/

答案 1 :(得分:1)

您可以使用换行符:

var queryParameters = "imagePath=" + encodeURIComponent(_image.source) 
    + "&saveMode=" + saveMode 
    + "&pageFolderId=" + pageFolderId 
    + "&id=" + pageId 
    + "&parent=" + parent
    + "&quality=" + sQuality.value 
    + "&commands=" + commandQueue.Serialize();

答案 2 :(得分:0)

您可以将所有数据放入数组中,然后执行连接。通常,数组的连接比连接更快,但如果你不多次构建这个字符串应该没有区别。

var arr = [];
arr[1] = "item1";
arr[2] = "item2";
arr[3] = "item3";
var result = arr.join('');

这样写它可以提高可读性和调试性。您可以非常轻松地评论一个参数。

答案 3 :(得分:0)

怎么样:

function qSerialize(obj){
  var q = [];
  for (var l in obj) {
   if (obj.hasOwnProperty(l)){
     q.push(l+'='+obj[l]);
   }
  }
  return q.join('&');
}

var qParamStr = qSerialize( 
 {
  imagePath: encodeURIComponent(_image.source),
  saveMode: saveMode,
  pageFolderId: pageFolderId,
  id: pageId,
  parent: parent,
  quality: sQuality.value,
  commands: commandQueue.Serialize()
 }
);