将对象键和值添加到URL Query

时间:2016-08-19 16:57:13

标签: javascript jquery arrays pushstate

我有一个更新URL查询字符串的函数。在某些情况下它工作正常,我有单键和值数组,但当我有多个值的数组键时,它不会将它附加到查询字符串,但如果我看到对象,我可以看到键及其值。以下是我的功能

function Querystring(obj) {
var querystring = "";
// Build the query string
var currentQueryString = parseQueryString();
var newQueryString = "";
var dataCategory = Object.keys(obj)[0];
console.log(dataCategory);
// Set the new value
if (obj[dataCategory] != null) {
    currentQueryString[dataCategory] = obj[dataCategory].join(",");
    // Loop the keys in currentQueryString and contruct new querystring
    Object.keys(currentQueryString).forEach(function (key, index) {
        if (index == 0) {
            newQueryString += "?" + key + "=" + currentQueryString[key];
        } else {
            newQueryString += "&" + key + "=" + currentQueryString[key];
        }
    });
}
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + newQueryString;

window.history.pushState({ path: newurl }, '', newurl);

return newQueryString;

}

这就是我调用此函数的方式

$('.select').change(function () {
                var SortOrder = $(this).attr("id");
                var SortBy = $(this).data("sortby");
                var obj = {};
                obj[SortOrder] = $(this).val();
                obj[SortBy] = [$('option:selected', this).data("price")];
                Querystring(obj);
            });

提前致谢

2 个答案:

答案 0 :(得分:0)

你可以这么简单一点。试试下面的例子。忽略getParser函数,因为它只是让我们能够测试此代码。



function getParser(url) {
  var a = document.createElement("a");
  a.href = url;
  return a;
}  

function getUpdatedURL(url, newQueryParams) {
  var searchParams = url.search.substring(1).split("&");
  var obj = {};
  searchParams.forEach(function(param){
    var paramParts = param.split("=");
    obj[paramParts[0]] = paramParts[1];
  });
  obj = Object.assign(obj, newQueryParams);
  url.search = "?"+Object.keys(obj).map(p => p+"="+obj[p]).join("&");
  return url.href;
}

var url = getParser("http://example.com/test/page?blah=abc&test=123"); 

//Ignore this as this is just for us to be able to test and run this example. You'll pass in the window.location instead of the url variable defined here.
console.log(getUpdatedURL(url, { sortOrder: "1345", sortBy: ["price","other","more"] }));




答案 1 :(得分:0)

为它编写代码非常简单,但为了获得完整的果汁,我建议使用这个小库:

  

https://www.npmjs.com/package/query-string

我编写了自己的代码来构建和破坏查询字符串,但我切换到了这个,因为它给出了完整的彩虹。

用法

const queryString = require('query-string');

console.log(location.search);
//=> '?foo=bar' 

const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'} 

console.log(location.hash);
//=> '#token=bada55cafe' 

const parsedHash = queryString.parse(location.hash);
console.log(parsedHash);
//=> {token: 'bada55cafe'} 

parsed.foo = 'unicorn';
parsed.ilike = 'pizza';

const stringified = queryString.stringify(parsed);
//=> 'foo=unicorn&ilike=pizza' 

location.search = stringified;
// note that `location.search` automatically prepends a question mark 
console.log(location.search);
//=> '?foo=unicorn&ilike=pizza'