Efficient JavaScript Object Encoding for Query Strings
Encoding a JavaScript object into a string for transmission via GET requests can be a tedious task. Thankfully, there's a straightforward JavaScript solution that doesn't rely on third-party libraries or jQuery.
Here's how you can do it:
serialize = function(obj) { var str = []; for (var p in obj) if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&"); }
This function takes a JavaScript object as input and returns an encoded string. The encoding process involves:
To illustrate, consider encoding the following object:
{ foo: "hi there", bar: "100%" }
Using the serialize function:
console.log(serialize({ foo: "hi there", bar: "100%" }));
Will output the following encoded string:
foo=hi%20there&bar=100%25
This encoded string can then be passed as a query string in a GET request without any hassle.
The above is the detailed content of How Can I Efficiently Encode a JavaScript Object into a Query String?. For more information, please follow other related articles on the PHP Chinese website!