G
G
Gabe Jonson2017-07-15 18:17:35
JavaScript
Gabe Jonson, 2017-07-15 18:17:35

How to convert data for a request to the server?

I ask for help, the problem is this:
there is a normal Fetch ()
in it's body, but as I understand it, body must be sent in the format
foo=foo&bar=bar
, but ok, these are 2 elements, but what if there are 100500 of them ?!
And now the question itself arises ... How from

{
 foo: 'foo',
 bar: 'bar'
}

do
foo=foo&bar=bar

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stalker_RED, 2017-07-15
@gabejonson

const params = { foo: 'foo', bar: 'bar' };
const urlParams = new URLSearchParams(Object.entries(params));
fetch('/some/url?' + urlParams);

MDN: URLSearchParams Not
supported everywhere, the polyfill can be found here .

V
Valery, 2017-07-15
@supervaleha

serialize = function(obj, prefix) {
  var str = [], p;
  for(p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
      str.push((v !== null && typeof v === "object") ?
        serialize(v, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
  }
  return str.join("&");
}

console.log(serialize({foo: "hi there", bar: { blah: 123, quux: [1, 2, 3] }}));
// foo=hi%20there&bar%5Bblah%5D=123&bar%5Bquux%5D%5B0%5D=1&bar%5Bquux%5D%5B1%5D=2&bar%5Bquux%5D%5B2%5D=3

I think what you need. Found here .

T
twobomb, 2017-07-15
@twobomb

var obj = {
 foo: 'foo',
 bar: 'bar'
};

var str  = "";
for(var key in obj)
  str+=key+"="+obj[key]+"&";
 str = str.substr(0,str.length-1);
 alert(str)//foo=foo&bar=bar

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question