jQuery append params to url jQuery append params to url ajax ajax

jQuery append params to url


Since other replies didn't answer my question, i have made a few tests with the $.ajax() call to see how it merges urls with param data.

My findings so far:

  • if url contains a ?, then $.ajax() will append '&' + $.param(data)
  • if not, then $.ajax() will append '?' + $.param(data)

So if I want to keep my url processing function consistent with the way $.ajax() does it, then it should be something like the following:

  var addParams = function( url, data )  {    if ( ! $.isEmptyObject(data) )    {      url += ( url.indexOf('?') >= 0 ? '&' : '?' ) + $.param(data);    }    return url;  }

I am still wondering if there is a built-in jQuery method to do this.


You can build query string like this:

getQueryStr = 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({    param1: "val1",    param2: "val2"}));

For recursive :

getQueryStr = function(obj, prefix) {    var str = [];    for (var p in obj) {        if (obj.hasOwnProperty(p)) {            var k = prefix ? prefix + "[" + p + "]" : p,                v = obj[p];            str.push(typeof v == "object" ?                getQueryStr(v, k) :                encodeURIComponent(k) + "=" + encodeURIComponent(v));        }    }    return str.join("&");}console.log(serialize({    favfruit: "apple",    data: {        name: 'js',        points: [1, 2, 3]    }}));


yes you can use jqueries .param() function to do this.

jsfiddle demo

var params = { param1:"foo", param2:"bar"};var str = jQuery.param( params );alert(str);