Serialize Object to Query String in JavaScript/Jquery

Serialize object to query string in JavaScript/jQuery

You want $.param(): http://api.jquery.com/jQuery.param/

Specifically, you want this:

var data = { one: 'first', two: 'second' };
var result = $.param(data);

When given something like this:

{a: 1, b : 23, c : "te!@#st"}

$.param will return this:

a=1&b=23&c=te!%40%23st

How to serialize an Object into a list of URL query parameters?

var str = "";
for (var key in obj) {
if (str != "") {
str += "&";
}
str += key + "=" + encodeURIComponent(obj[key]);
}

Example: http://jsfiddle.net/WFPen/

Flatten a javascript object to pass as querystring

You want jQuery.param:

var str = $.param({ cost: 12345, insertBy: 'testUser' });
// "cost=12345&insertBy=testUser"

Note that this is the function used internally by jQuery to serialize objects passed as the data argument.

Query-string encoding of a JavaScript object

Like this:

serialize = function(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}

console.log(serialize({
foo: "hi there",
bar: "100%"
}));
// foo=hi%20there&bar=100%25

How can I convert an object to a query string?

There is an excellent URL library, URL.js which works pretty much as you describe for queries.

For your example, the code would be:

URI().addSearch({ hello: '123', goodbye: "789" }).toString()

This produces the result with a pre-pended ?, but it comes in extremely handy for constructing & manipulating real URLs.

ASP.NET core, jQuery.get, how to serialize array in query string?

After much searching, I eventually stumbled on the following post, which should work well enough. It seems like the model binding formats for .NET core have changed considerably, and so it's no longer compatible with jquery conventions.

Serialize array to query string parameter

You can fix it adding to $.ajax parameter traditional: true.

Here you can find reference why

I need to transport a javascript object via query string

You want Douglas Crockford's json2.js: https://github.com/douglascrockford/JSON-js

var test = new Object();
test.date = new Date();
test.str = "hello world!";

var dest = 'http://mywebservice?'+encodeURIComponent( JSON.stringify(test) );

(oh, and don't use escape(), it's deprecated. Always use encodeURIComponent() instead)

But why not use a (session) cookie instead? Using the URI to pass data can be a major problem for SEO, for bookmarks, for links, etc.



Related Topics



Leave a reply



Submit