DerNalia
DerNalia

Reputation: 327

How do I append a JSON object to a GET url?

Making a GET request is easy, you just specify an URL in the href attribute of an anchor tag.

But, how do you add a JSON object to that URL?

I'm guessing this has to be done through jQuery... but I can't user AJAX, or the response isn't rendered by the browser.

so far, I've tried this: $j("#gen").attr("href", $j("#gen").attr("href") + "?" + JSON.stringify({object: data})); but it doesn't append the data. This is triggered onClick

Upvotes: 0

Views: 5539

Answers (3)

NullVoxPopuli
NullVoxPopuli

Reputation: 65143

This should work:

jQuery("#gen").attr("href", jQuery("#gen").attr("href") + "?" + jQuery.param({object: data}));

Upvotes: 1

Josh
Josh

Reputation: 44916

Any values in a GET request are expected to be URL encoded into the request string.

There is a jQuery.get() function that will do this for you, but all it does is serialize a set of name/value pairs as query string parameters.

I'm not really sure what you mean by not being able to use AJAX. Using jQuery you would do something like this:

$.get("foo/bar", { foo: "foo", bar: "bar" },
   function(data){
     $("#myTarget").append(data);
   });

Assuming of course the return value was HTML.

Ok, I think I understand a little better. If you just want to turn some object into a Query String, then you can roll your own function pretty easy:

function toQueryString(obj){
    var formattedVals = [];

    for(var prop in obj){
        formattedVals.push(prop + "=" + obj[prop]);
    }

    return formattedVals.join("&");
}

You can see how it would work by calling it this way:

var data = { foo: "foo", bar: "bar" };

alert(toQueryString(data));

Anyway, this should get you 90% of the way there.

Upvotes: 3

bryanmac
bryanmac

Reputation: 39296

A GET request has querystring params. If it's a GET request you really want, then you can map properties on the object to key value pairs on the request.

For example:

JSON object:  { prop1: val1, prop2: val2 } 
url get querystring:  ?prop1=val1&prop2=val2

But, if you want to send an object to the server, perhaps you really want a POST? In that case, the JSON object would be in the body of the POST.

Upvotes: 2

Related Questions