我正在为 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/