Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert javascript object to URL parameters

I realize that fundamentally I'm probably going about this the wrong way so I'm open to any pushes in the right direction.

I'm trying to use the HipChat API to send a notification to a room like so:

https://www.hipchat.com/docs/api/method/rooms/message

I'm trying to build the URL in the example with a js object's parameters, so basically I'm trying to convert this:

var hipChatSettings = {             format:"json",             auth_token:token,             room_id: 1,             from: "Notifications",             message: "Message"         } 

To this:

https://api.hipchat.com/v1/rooms/message?format=json&auth_token=token&room_id=1&from=Notifications&message=Message

like image 797
user2865446 Avatar asked Mar 27 '14 04:03

user2865446


People also ask

How to turn an object into query string parameters in javascript?

Use the URLSearchParams() constructor to convert an object to a query string, e.g. new URLSearchParams(obj). toString() . Calling the toString() method on the result returns a query string without the question mark. If the provided object is empty, an empty string is returned.

Can you use Javascript to get URL parameter values?

The short answer is yes Javascript can parse URL parameter values. You can do this by leveraging URL Parameters to: Pass values from one page to another using the Javascript Get Method. Pass custom values to Google Analytics using the Google Tag Manager URL Variable which works the same as using a Javascript function.

How do you turn a URL into an object?

Use the URLSearchParams constructor to convert a query string to an object, e.g. const obj = new URLSearchParams('? page=3&filter=js') . The constructor returns an object instance from which we can access the query string parameters using the get() method, e.g. obj.


1 Answers

You should check this jQuery.param function.

var params = { width:1680, height:1050 };  var str = jQuery.param( params );  console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 88
Mithun Satheesh Avatar answered Sep 18 '22 13:09

Mithun Satheesh