Search code examples
javascriptjquerygetjson

getJSON() - how to remove AND-sign in front of data param?


I'm doing the following jQuery call:

$.getJSON(
"http://localhost:9000/user?name=",
"test",
function(data) {
alert(data.aaData[0]);}
);

but it doesn't work because the data param "test" will be "&test" in the actual call (at least that's what firebug tells me).

I'm a total beginner with JavaScript and jQuery, can anyone tell me how to remove the &-sign in front of the data param? So that the actual call is http://localhost:9000/user?name=data and not http://localhost:9000/user?name=&data


Solution

  • You could pass the data as an object, like this:

    $.getJSON(
        "http://localhost:9000/user",
        { name: "test" },
        function(data) {
            alert(data.aaData[0]);
        }
    );
    

    The data-object will then be converted to a string and URL-encoded before it is added to the URL. From the jQuery documentation of .getJSON():

    If the value of the data parameter is an object (map), it is converted to a string and url-encoded before it is appended to the URL.