【问题标题】:Javascript Reload page with change in param values when params are in no particular order当参数没有特定顺序时,Javascript重新加载页面,参数值发生变化
【发布时间】:2014-12-31 21:12:08
【问题描述】:

我需要在更新参数值后重新加载页面位置,如果参数始终按特定顺序排列,这并不难,但它们不是。

所以如果有一个固定的模式,我可以通过正则表达式匹配来定位它们,例如一个 URL: http://www.example.html?sf_id=15040&15041.survey=form&variation=25002_1

我的目标是这样的:

window.location.replace( window.location.href.replace( sf_id=\d+&\d+\.survey=form&variation=, 'sf_id=460&460.survey=form&variation=25002_2' ) );

但是现在参数的出现是随机的,所以这些都是有效的 URL:

http://www.example.html?15041.survey=form&sf_id=15040&variation=25002_1
http://www.example.html?variation=25002_1&sf_id=15040&15041.survey=form
http://www.example.html?param1=value1&variation=25002_1&sf_id=15040&param2=value2&15041.survey=form

我知道我仍然可以正确 if/else if 语句,但我认为这不是正确的方式,因为没有特定的模式。

感谢任何帮助!谢谢。

【问题讨论】:

    标签: javascript url query-string url-parameters url-parsing


    【解决方案1】:

    请参阅if this answer 将带您进入赛道。之后,您可以进行各种对象与对象的比较以检查它们是否匹配。

    【讨论】:

      【解决方案2】:

      基于this SO answer,我将使用以下代码获取所有查询参数的数组:

      var qs = (function(a) {
          if (a == "") return {};
          var b = {};
          for (var i = 0; i < a.length; ++i)
          {
              var p=a[i].split('=', 2);
              if (p.length == 1)
                  b[p[0]] = "";
              else
                  b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
          }
          return b;
      })(window.location.search.substr(1).split('&'));
      

      更新
      上面的函数返回一个关联数组,所以你不能像我之前回答的那样使用.join()。相反,您必须遍历键并重建新的查询字符串。我还包含了一个替换参数键的函数——你可能想多了。

      function replaceParamKey(qsObj, oldKey, newKey) {
          qsObj[newKey] = qsObj[oldKey];
          delete qsObj[oldKey];
      }
      
      function constructQueryString(qsObj) {
          var qsString = "?",
              c = 0;
          for (var param in qsObj) {
              if (c) qsString += "&";
              qsString += encodeURIComponent(param);
              if (qsObj[param] !== "") qsString += ("=" + encodeURIComponent(qsObj[param]));
              c++;
          }
      
          return qsString;
      }
      
      console.info(qs); // Object {15041.survey: "form", sf_id: 15040, variation: "25002_1"}
      replaceParamKey(qs, "15041.survey", "460.survey");
      console.info(constructQueryString(qs)); // ?sf_id=15040&variation=25002_1&460.survey=form
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 2011-09-09
      • 2014-10-29
      • 1970-01-01
      相关资源
      最近更新 更多