是否有一个快速和简单的方法来编码JavaScript对象到字符串,我可以通过GET请求传递?
没有jQuery,没有其他框架-只有纯JavaScript:)
是否有一个快速和简单的方法来编码JavaScript对象到字符串,我可以通过GET请求传递?
没有jQuery,没有其他框架-只有纯JavaScript:)
当前回答
jQuery有一个函数jQuery.param()。如果你已经在使用它,你可以使用这个:
例子:
var params = { width:1680, height:1050 };
var str = jQuery.param( params );
STR现在包含宽度=1680&高度=1050。
其他回答
另一种方法(没有递归对象):
getQueryString = function(obj)
{
result = "";
for(param in obj)
result += ( encodeURIComponent(param) + '=' + encodeURIComponent(obj[param]) + '&' );
if(result) //it's not empty string when at least one key/value pair was added. In such case we need to remove the last '&' char
result = result.substr(0, result.length - 1); //If length is zero or negative, substr returns an empty string [ref. http://msdn.microsoft.com/en-us/library/0esxc5wy(v=VS.85).aspx]
return result;
}
alert( getQueryString({foo: "hi there", bar: 123, quux: 2 }) );
const serialize = obj => Object.keys(obj).reduce((a, b) =>
a.push(encodeURIComponent(b) + "=" + encodeURIComponent(obj[b])) && a,
[]).join("&");
电话:
console.log(serialize({a:1,b:2}));
// output: 'a=1&b=2
'
PHP符号的TypeScript版本(没有URL转义版本)
/**
* Converts an object into a Cookie-like string.
* @param toSerialize object or array to be serialized
* @param prefix used in deep objects to describe the final query parameter
* @returns ampersand separated key=value pairs
*
* Example:
* ```js
* serialize({hello:[{world: "nice"}]}); // outputs "hello[0][world]=nice"
* ```
* ---
* Adapted to TS from a StackOverflow answer https://stackoverflow.com/a/1714899/4537906
*/
const serialize = (toSerialize: unknown = {}, prefix?: string) => {
const keyValuePairs = [];
Object.keys(toSerialize).forEach((attribute) => {
if (Object.prototype.hasOwnProperty.call(toSerialize, attribute)) {
const key = prefix ? `${prefix}[${attribute}]` : attribute;
const value = toSerialize[attribute];
const toBePushed =
value !== null && typeof value === "object"
? serialize(value, key)
: `${key}=${value}`;
keyValuePairs.push(toBePushed);
}
});
return keyValuePairs.join("&");
};
我建议使用URLSearchParams接口:
const searchParams = new URLSearchParams(); Const params = {foo: "hi there", bar: "100%"}; 种(params)。forEach(key => searchParams。追加(关键,params[主要])); console.log (searchParams.toString ())
或者像这样将搜索对象传递给构造函数:
Const params = {foo: "hi there", bar: "100%"}; const queryString = new URLSearchParams(params).toString(); console.log(参数);
单行转换对象为查询字符串,以防有人再次需要它:
let Objs = { a: 'obejct-a', b: 'object-b' }
Object.keys(objs).map(key => key + '=' + objs[key]).join('&')
// The result will be a=object-a&b=object-b