0

我在 Stack Overflow 上找到了这个脚本:

window.params = function(){
    var params = {};
    var param_array = window.location.href.split('?')[1].split('&');
    for(var i in param_array){
        x = param_array[i].split('=');
        params[x[0]] = x[1];
    }
    return params;
}();

这会将 URL 拆分为数据,就像 PHP 对$_GET.

我有另一个函数,它使用它并刷新 iframe。如果其中一些数据存在,我想从 URL 获取数据并添加另一个数据。Firebug告诉我,那search是没有定义的,但是为什么呢?

function RefreshIFrames(MyParameter) {
    var cat = window.params.cat;
    var category = window.params.category;
    var search = window.params.search;

    if (search.length>0 && category.length>0){
        window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search="+search+"&category="+category+"&rendez="+MyParameter;
    }

    if (cat.length>0){
        window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat="+cat+"&rendez="+MyParameter;
    }

    if (cat.length==0 && category.length==0 && search.length==0){
        window.location.href="http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez="+MyParameter;
    }
    alert(window.location);
}
4

1 回答 1

0

如果要添加集合点或更改现有集合点,请执行此操作 - 我假设 URL 实际上以http://siriusradio.hu/kiskunfelegyhaza/video/index.php开头,因此无需创建它。让我知道您是否需要与您提供的 URL 不同的 URL

参数片段不能正常工作(因为 in 不应在普通数组上使用)

这是经过测试的代码

function getParams(passedloc){
  var params = {}, loc = passedloc || document.URL;
  loc = loc.split('?')[1];
  if (loc) {
    var param_array = loc.split('&');
    for(var x,i=0,n=param_array.length;i<n; i++) {
      x = param_array[i].split('=');
      params[x[0]] = x[1];
    }
  }
  return params;
};

function RefreshIFrames(MyParameter,passedloc) { // if second parm is specified it will take that 
  var loc = passedloc || document.URL; // 
  window.param = getParams(loc); 
  loc = loc.split("?")[0]+"?"; // will work with our without the ? in the URL
  for (var parm in window.param) {
    if (parm != "rendez") loc += parm +"="+ window.param[parm]+"&";
  }
  // here we have a URL without rendez but with all other parameters if there
  // the URL will have a trailing ? or & depending on existence of parameters
  loc += "rendez="+MyParameter;
  window.console && console.log(loc)
  // the next statement will change the URL
  // change window.location to window.frames[0].location to change an iFrame
  window.location = loc; 
}

// the second parameter is only if you want to change the URL of the page you are in
RefreshIFrames("rendez1","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?cat=cat1&search=search1");
RefreshIFrames("rendez2","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?search=search2");
RefreshIFrames("rendez3","http://siriusradio.hu/kiskunfelegyhaza/video/index.php?rendez=xxx&search=search2");
RefreshIFrames("rendez4","http://siriusradio.hu/kiskunfelegyhaza/video/index.php");

// here is how I expect you want to call it    
RefreshIFrames("rendez5"​); // will add or change rendez=... in the url of the current page
于 2012-10-17T07:33:27.933 回答