如何从URL查询字符串中获取参数值

时间:2014-11-01 18:54:57

标签: javascript

如何解析以下网址查询字符串以获取数量参数的值?

  

myurl /频道/ BuyCredits?量= 2

我尝试过很多例子没有成功:

我刚试过这个例子:

  marvmentApp.controller("channelCreditController", function($scope, $http, $compile, $location) {
    var params, test2;
    $scope.parseQueryString = function() {
      var objURL, str;
      str = window.location.search;
      objURL = {};
      str.replace(new RegExp("([^?=&]+)(=([^&]*))?", "g"), function($0, $1, $2, $3) {});
      objURL[$1] = $3;
      return;
      return objURL;
    };
    params = $scope.parseQueryString();
    test2 = params['quantity'];
    debugger;
  });

我一直收到错误$ 1是udefined

1 个答案:

答案 0 :(得分:1)

使用JavaScript location.search属性。它将返回您的URL的查询字符串(包括“?”符号)。

如果网址为http://www.example.org/index.php?param=arg

location.search?param=arg

要删除“?”,请使用JS替换方法:

var url = "?param=arg"; // pretend that the variable "url" is the query string
url = url.replace(/[\?]/,"");
document.getElementById('output').innerHTML = "Query string is: \"" + url + "\"";
<p id="output"></p>

希望这有帮助!