jquery - More concise way to construct a query string in JavaScript -


i don't write lot of javascript. following code works, there more concise way of writing this? want construct query string appended url variables possibly null. if values null, want empty string. jquery available me use (and using it).

constructquerystring = function(code, flag) {     var qsobj = {};      if ( code ) {         qsobj["code"] = code;     }     if ( flag ) {         qsobj["flag"] = flag;     }     return ( !$.isemptyobject(qsobj) ) ? "?" + $.param(qsobj) : ""; } 

some tests:

console.log(constructquerystring("xxxxxx", "true")); // ?code=xxxxxx&flag=true console.log(constructquerystring(null, "true")); // ?flag=true console.log(constructquerystring("xxxxxx", null)); // ?code=xxxxxx console.log(constructquerystring(null, null)); // (an empty string) 

update: below more context showing how using code in our project.

code = $el.attr("data-code") || null; flag = $el.attr("data-flag") || null; qsobj = {};  if ( code ) {     qsobj["code"] = code; } if ( flag ) {     qsobj["flag"] = flag; } querystring = ( !$.isemptyobject(qsobj) ) ? "?" + $.param(qsobj) : "";  $.ajax({     "type": "post", "contenttype": "application/json; charset=utf-8",     "url": url + querystring,     "data": json.stringify(reqbody) }); 


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -