JavaScript 函数将 JSON 键值对象转换为查询字符串
我正在努力格式化 Facebook Feed Dialog 的网址。不过参数实在是太多了。我想要为这些对话框提供一个功能,例如:
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()
是正确使用的函数吗?
我被困在情人源代码。
更新:因为我们使用的是 jQuery,所以我使用 jQuery.each
重写了该方法。我还按照 @galambalazs & 的建议,用 encodeURIComponent()
替换了 escape()
。 @TJ克劳德。谢谢你们!
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("&");
}
它正在工作!
I'm working on formatting a URL for the Facebook Feed Dialog. There's so many parameters though. I want to have a function for these dialogs, something like:
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("&")
}
Oh wow... I think I just answered my own question. Is that right? Is escape()
the correct function to use?
I'm stuck in the Lovers source code.
UPDATE: Since, we're using jQuery, I rewrote the method using jQuery.each
. I also replaced escape()
with encodeURIComponent()
as suggested by @galambalazs & @T.J. Crowder. Thanks, guys!
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("&");
}
It's working!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更好的是,使用
encodeURIComponent
代替。请参阅这篇文章比较两者:Better yet, use
encodeURIComponent
instead. See this article comparing the two:有一个 jQuery 方法可以完成此操作:$.param。它会像这样工作:
There is a jQuery method to accomplish this: $.param. It would work like this:
例子:
Example:
示例:
结果:
example:
Result: