将 JSON 键值对象转换为查询字符串的 JavaScript 函数

标签 javascript json iterator escaping urlencode

我正在为 Facebook Feed Dialog 格式化一个 URL .虽然有很多参数。我想为这些对话框提供一个功能,例如:

function generateDialogUrl(dialog, params) {
  base  = "http://www.facebook.com/dialog/" + dialog + "?";
  tail = [];
  for (var p in params) {
    if (params.hasOwnProperty(p)) {
      tail.push(p + "=" + escape(params[p]));
    }
  }
  return base + tail.join("&")
}

哦哇...我想我刚刚回答了我自己的问题。是对的吗? escape() 是正确的函数吗?

我卡在了Lovers source code .

更新:由于我们使用的是 jQuery,因此我使用 jQuery.each 重写了该方法。我还按照@galambalazs 和@T.J 的建议用encodeURIComponent() 替换了escape()。拥挤。谢谢,伙计们!

var generateDialogUrl = function (dialog, params) {
  base  = "http://www.facebook.com/dialog/" + dialog + "?";
  tail = [];
  $.each(params, function(key, value) {
    tail.push(key + "=" + encodeURIComponent(value));
  })
  return base + tail.join("&");
}

成功了!

最佳答案

更好的是,使用 encodeURIComponent反而。看这个article两者比较:

The escape() method does not encode the + character which is interpreted as a space on the server side as well as generated by forms with spaces in their fields. Due to this shortcoming and the fact that this function fails to handle non-ASCII characters correctly, you should avoid use of escape() whenever possible. The best alternative is usually encodeURIComponent().

escape() will not encode: @*/+

关于将 JSON 键值对象转换为查询字符串的 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4987381/

相关文章:

javascript - 对于空对象给出 TypeError : Cannot convert undefined or null to object

javascript - 动态添加行到表后,jQuery 选择器未触发

javascript - 使用 jquery 隐藏/关闭按钮

java - jackson 自定义号码解析

java - Jackson JSON 处理器问题

php - 谷歌地理编码不适用于数据库中具有特殊字符的地址

c++ - 如何将 find_if 与链表等非容器一起使用?

javascript - React.js,如何避免 var me = this?

java - 为什么当参数和参数匹配时会发生 javac 错误 "(x) cannot be applied to (y)"? (内部类调用外部类方法)

c++ - C++中映射中迭代器概念的混淆