简体   繁体   English

Javascript Pass获取参数

[英]Javascript pass get params

I get exists get params on request: 我得到存在,应要求提供参数:

?filterBy=1,2,3

How I can pass params after filterBy with js? 我如何在使用js filterBy之后传递参数?

My solution: 我的解决方案:

switch(type) {
        case 'status':
            window.location.href = '?filter-status=i=' + filters;
        break;
        case 'oldFrom':
            window.location.href = '?oldFrom';
        break;
        case 'oldTo':
            window.location.href = '?oldTo';
        break;
        case 'newFrom':
            window.location.href = '?newFrom';
        break;
        case 'newTo':
            window.location.href = '?newTo';
        break;
        case 'catesel':
            window.location.href = '?byCategory=' + filters;
        break;
    }

In my case I rewrite get params. 就我而言,我重写了get params。
Example: if I have exists param on request: byCategory=1,2,3 And when I click button to add new filter by request is remove and write new. 示例:如果我根据请求存在参数: byCategory=1,2,3当我单击按钮以按请求添加新过滤器时,将删除并编写新参数。 How I can do this: 我该怎么做:

?byCategory=1,2,3&newFrom ... ?byCategory=1,2,3&newFrom ...

I need remove window.location.href or how pass exists get params? 我需要删除window.location.href或如何通过存在获取参数?

For getting params from your url, use URL constructor: 要从您的网址获取参数,请使用网址构造函数:

const url = new URL("?filterBy=1,2,3");
const filterBy = url.searchParams.get("filterBy");
console.log(filterBy);

If you need to get array of values, just split it into array 如果需要获取值数组,只需将其拆分为数组

const myArrOfFilters = filterBy.split(',');
console.log(myArrOfFilters);

Use URLSearchParams to get query string values 使用URLSearchParams获取查询字符串值

var params = '';
var type = 'status';
var filters = '1,2';

switch (type) {
 case 'status':
  params = '?filter-status-i=' + filters;
  break;
 case 'oldFrom':
  params = '?oldFrom';
  break;
 case 'oldTo':
  params = '?oldTo';
  break;
 case 'newFrom':
  params = '?newFrom';
  break;
 case 'newTo':
  params = '?newTo';
  break;
 case 'catesel':
  params = '?byCategory=' + filters;
  break;
}
//window.location.href = params
var urlParams = new URLSearchParams(params);
console.log(urlParams.get('filter-status-i'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM