如何解析以下 URL 查询字符串以获取数量参数的值?
myurl/Channels/BuyCredits?quantity=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 is udefine
最佳答案
使用 JavaScript location.search
属性。它将返回您的 URL 的查询字符串(包括“?”符号)。
如果 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>
希望这有帮助!
关于javascript - 如何从 URL 查询字符串中获取参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26691926/