jQuery.param的普通的JavaScript当量()当量、普通、jQuery、param

2023-09-10 22:15:16 作者:小二、来碗大姨妈

jQuery.param()需要一个数组键 - 值对的,并把它变成可以作为在HTML请求查询字符串用的字符串。例如,

jQuery.param() takes an array of key-value pairs, and turns it into a string you can use as a query string in HTML requests. For example,

a = {
      userid:1,
      gender:male
    }

将被转换为

userid=1&gender=male

我试图调用外部的API上的谷歌Apps脚本在服务器端,这需要很长的查询字符串。我会使用jQuery的参数功能,但似乎没有简单的方法来使用jQuery在谷歌的服务器端。

I'm trying to call external APIs on the server side in a Google Apps script, which need long query strings. I would use the jQuery param function, but there seems to be no easy way to use jQuery on the server side in Google.

你能不能给我普通的JavaScript code,可实现相同的功能?

jQuery的实现是此处,但我不希望被简单地复制并剥开code处理去冒险跳过任何关键的细节传统。

The jQuery implementation of it is here, but I don't want to take chances skipping over any crucial details by simply copying it and ripping out the code dealing with 'traditional'.

推荐答案

您也可以做到这一点与纯JavaScript,但你必须写更多的行code。试试这个:

You can also do that with pure JavaScript, but you have to write more lines of code. Try this:

HTML code来进行测试:

HTML code for testing:

<p id="test"></p>

JavaScript以被解雇的onload:

JavaScript to be fired onload:

a = {
      userid:1,
      gender: "male",
    }

url = Object.keys(a).map(function(k) {
    return encodeURIComponent(k) + '=' + encodeURIComponent(a[k])
}).join('&')

document.getElementById("test").innerHTML=url

输出是这样的:

The output is this:

userid=1&gender=male

您可以在JSFIDDLE.NET试试这个,它的工作原理,这里的链接: http://jsfiddle.net/ert93wbp/

You can try this on JSFIDDLE.NET, it works, here's the link: http://jsfiddle.net/ert93wbp/