网站建设之使用JavaScript获取URL参数

url参数(也称为查询字符串参数或url变量)用于通过url从页面到页面或从客户端到服务器发送少量数据。它们可以包含各种有用的信息,例如搜索查询,链接引荐,产品信息,用户首选项等。
在本文中,我们将向您展示如何使用javascript解析和操作url参数。
本文针对相关性和准确性在2020年进行了更新。
获取url参数在现代浏览器中,这要归功于urlsearchparams接口,这变得容易得多。这定义了许多实用程序方法来使用url的查询字符串。
假设我们的url是https://example.com/?product=shirt&color=blue&newuser&size=m,我们可以使用window.location.search以下命令获取查询字符串:
const querystring = window.location.search; console.log(querystring); // ?product=shirt&color=blue&newuser&size=m 然后,我们可以使用解析查询字符串的参数urlsearchparams:
const urlparams = new urlsearchparams(querystring); 然后,我们对结果调用其任何方法。
例如,urlsearchparams.get()将返回与给定搜索参数关联的第一个值:
const product = urlparams.get('product') console.log(product); // shirt const color = urlparams.get('color') console.log(color); // blue const newuser = urlparams.get('newuser') console.log(newuser); // empty string 其他有用的方法检查参数是否存在您可以urlsearchparams.has()用来检查某个参数是否存在:
console.log(urlparams.has('product')); // true console.log(urlparams.has('paymentmethod')); // false 获取所有参数值您可以urlsearchparams.getall()用来返回与特定参数关联的所有值:
console.log(urlparams.getall('size')); // [ 'm' ] //programmatically add a second size parameter. urlparams.append('size', 'xl'); console.log(urlparams.getall('size')); // [ 'm', 'xl' ] 遍历参数urlsearchparams还提供了一些熟悉的object迭代器方法,使您可以迭代其键,值和条目:
const keys = urlparams.keys(), values = urlparams.values(), entries = urlparams.entries(); for (const key of keys) console.log(key); // product, color, newuser, size for (const value of values) console.log(value); // shirt, blue, , m for(const entry of entries) { console.log(`${entry[0]}: ${entry[1]}`); } // product: shirt // color: blue // newuser: // size: m 浏览器支持浏览器对的支持urlsearchparams很好。在撰写本文时,所有主流浏览器均支持该功能。
如果您必须支持internet explorer等旧版浏览器,则可以使用polyfill。或者,您可以继续阅读本教程的其余部分,并学习如何进行自己的学习。
滚动您自己的查询字符串解析功能让我们继续使用上一节中使用的url:
http://example.com/?product=shirt&color=blue&newuser&size=m 这是一个为所有url参数提供一个整洁对象的函数:
function getallurlparams(url) { // get query string from url (optional) or window var querystring = url ? url.split('?')[1] : window.location.search.slice(1); // we'll store the parameters here var obj = {}; // if query string exists if (querystring) { // stuff after # is not part of query string, so get rid of it querystring = querystring.split('#')[0]; // split our query string into its component parts var arr = querystring.split('&'); for (var i = 0; i < arr.length; i++) { // separate the keys and the values var a = arr[i].split('='); // set parameter name and value (use 'true' if empty) var paramname = a[0]; var paramvalue = typeof (a[1]) === 'undefined' ? true : a[1]; // (optional) keep case consistent paramname = paramname.tolowercase(); if (typeof paramvalue === 'string') paramvalue = paramvalue.tolowercase(); // if the paramname ends with square brackets, e.g. colors[] or colors[2] if (paramname.match(/\[(\d+)?\]$/)) { // create key if it doesn't exist var key = paramname.replace(/\[(\d+)?\]/, ''); if (!obj[key]) obj[key] = []; // if it's an indexed array e.g. colors[2] if (paramname.match(/\[\d+\]$/)) { // get the index value and add the entry at the appropriate position var index = /\[(\d+)\]/.exec(paramname)[1]; obj[key][index] = paramvalue; } else { // otherwise add the value to the end of the array obj[key].push(paramvalue); } } else { // we're dealing with a string if (!obj[paramname]) { // if it doesn't exist, create property obj[paramname] = paramvalue; } else if (obj[paramname] && typeof obj[paramname] === 'string'){ // if property does exist and it's a string, convert it to an array obj[paramname] = [obj[paramname]]; obj[paramname].push(paramvalue); } else { // o
上一个:网站建设推广地址全面解读(上)
下一个:网站设计哪家公司好?怎样选择建站公司?
襄垣网站建设,襄垣做网站,襄垣网站设计