问题
I'm looking for an dependency-free implementation of jQuery.param(). I'm trying to create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request, without using jQuery.
I searched for some time now, but everyone just seems to use $.param()...
Thank you in advance!
回答1:
I found the best and optimal way on How to get query string values using JavaScript. Checkout the below example to fetch the query string.
var queryString = window.location.search || '';
var keyValPairs = [];
var params = {};
queryString = queryString.substr(1);
if (queryString.length)
{
keyValPairs = queryString.split('&');
for (pairNum in keyValPairs)
{
var key = keyValPairs[pairNum].split('=')[0];
if (!key.length) continue;
if (typeof params[key] === 'undefined')
params[key] = [];
params[key].push(keyValPairs[pairNum].split('=')[1]);
}
}
Usage of the above script
//url=http://stackoverflow.com/how-to-get-query-string-values-in-javascript?query=123&list=default
params['query'];
//Output ["123"]
params['list'];
//Output ["default"]
//Note: If the query string value is empty the method will return the value as empty string.
回答2:
if You need to get query string value using javascript
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
回答3:
If your object is a one dimension array like this:
var params = { input1:x, input2:y, input3: z };
Then a simple for loop can do the trick to serialize the object
var vals = '';
for(var key in params){
vals += key + '=' + paramas[key];
}
回答4:
Create a blank .js file (eg. GetQueryString.js) and copy the following code in it
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var urlParams = {};
(function () {
var e,
a = /\+/g,
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
urlParams[d(e[1])] = d(e[2]);
})();
Include GetQueryString.js file in your code
<script type="text/javascript" src="~/GetQueryString.js" />
If your key is in URL as follows
http://www.domain.com?key=123
key can be fetched from above URL by following call
var queryStringValue = getParameterByName("key");
来源:https://stackoverflow.com/questions/17493294/how-to-get-query-string-from-javascript-object-without-jquery