Query-string encoding of a Javascript Object

前端 未结 30 3676
渐次进展
渐次进展 2020-11-22 00:23

Do you know a fast and simple way to encode a Javascript Object into a string that I can pass via a GET Request?

No jQuery, no

30条回答
  •  感动是毒
    2020-11-22 00:49

    I suggest using the URLSearchParams interface:

    const searchParams = new URLSearchParams();
    const params = {foo: "hi there", bar: "100%" };
    Object.keys(params).forEach(key => searchParams.append(key, params[key]));
    console.log(searchParams.toString())

    Or by passing the search object into the constructor like this:

    const params = {foo: "hi there", bar: "100%" };
    const queryString = new URLSearchParams(params).toString();
    console.log(queryString);

提交回复
热议问题