为什么window.location.href.split(“?”)数组本身正在更改其值

时间:2018-05-03 06:40:42

标签: javascript arrays string browser location-href

我试图通过在URL中提供单选按钮的值作为查询参数来单击单选按钮(城市列表)来重新加载页面。假设我当前的网址是

http://localhost:3001/offers?category=Dining&sub_categories=Home%20Delivery&city=

在选择任何单选按钮时,我希望将其值添加到URL中的city参数中。 所以想要的URL应该是

http://localhost:3001/offers?category=Dining&sub_categories=Home%20Delivery&city=Mumbai

但问题是在修改网址时,sub_categories会自动被剥离,我得到的最终网址就是这个。

http://localhost:3001/offers?category=Dining&city=Mumbai

以下是我操作网址的代码:

$(document).on('click', '.city-selector' ,function(event) {
    event.preventDefault() ;
    var city_name = this.labels[0].textContent.trim().split("(")[0].trim() ;
    var location_string = window.location['href'].split('?');
    if(location_string.length > 1 && location_string[1].indexOf("city") > -1){
      var all_params = location_string[1].split("&") ;
      all_params.splice(all_params.indexOf("city=" + gon.selected_city), 1) ;
      all_params.splice(all_params.indexOf("localities=" + gon.selected_localities), 1) ;
      gon.selected_localities = '' ;
      location_string[1] = all_params.join("&") ;
      location_string[1] = location_string[1] + "&city=" + city_name ;
      window.location.href = location_string[0] + "?" +location_string[1] ;
    }

  }) ;

提示:问题在于排除 location_string = window.location['href'].split('?');当我记录location_string数组时,它不包含sub_categories参数 你确定哪一件事正在剥离它。

2 个答案:

答案 0 :(得分:1)

我认为您应该使用正则表达式来替换url:

var url = 'http://localhost:3001/offers?category=Dining&sub_categories=Home%20Delivery&city=';

var cityName = 'Mumbai';
var cityParams = 'city=' + cityName;


var newUrl = url + '&' + cityParams;
if (url.indexOf('?') === -1) {
    newUrl = url + '?' + cityParams;
} else if (url.indexOf('city=') > -1) {
    newUrl = url.replace(/(city=[\w\d%_]*)/g, cityParams);
}

它也与url一起工作: http://localhost:3001/offers?category=Dining?city=hanoi&sub_categories=Home%20Delivery

http://localhost:3001/offers

答案 1 :(得分:0)

实现这一目标的一种方法是:

var url = window.location.href;

var urlParams = url.split('?');

if(urlParams.length> 1){

urlParams = urlParams [1] .split('&');

urlParams.map(函数(PARAM){

task1 = af_op.PythonOperator(task_id='Data_Extraction_Environment',
                          provide_context=True,
                          python_callable=Task1, dag=dag1)

def Task1(**kwargs):
    return(kwargs['dag_run'].conf.get('file'))

})

window.location.href = url.split('?')[0] +'?' + urlParams.join('&');

}其他{

window.location.href = urlParams [0] +'?' +' city =' + city_name;

}