Javascript url重定向:这段代码有问题吗?

Javascript url redirection: Is there an issue with this code?

本文关键字:代码 有问题 重定向 url 段代码 Javascript      更新时间:2023-09-26

也许你能发现我看不到的东西:

这是我的代码

if(jQuery.urlParam('returnview')) {     
    var ret = jQuery.urlParam('returnview');
    var iid = jQuery.urlParam('iid'); 
    window.location = 'index.php?option=mycomponent&view='+ret+'&Itemid='+iid+'&lang=en';
} else  if(!jQuery.urlParam('returnview')){
  window.location = 'index.php?option=mycomponent&view=myview&Itemid=380&lang=en&sent=1'; 
} else {
  alert('something is dodge');
}

,这是函数:

jQuery.urlParam = function(name){
   var results = new RegExp('[''?&]' + name + '=([^&#]*)').exec(window.location.href);
   return results[1] || 0;
}

现在,如果有一个'returnview'定义在我的'from' URL,它工作得很好。然而,如果没有定义returnview,它应该转到第二种情况,或者即使失败,抛出一个警告。

有谁能看出我在这里做错了什么吗?

感谢雅克

你的第三个条件将永远不会被击中,因为你正在测试真/假,所以让我们删除它,留下你的:

if(jQuery.urlParam('returnview')) {     
    var ret = jQuery.urlParam('returnview');
    var iid = jQuery.urlParam('iid'); 
    window.location = 'index.php?option=mycomponent&view='+ret+'&Itemid='+iid+'&lang=en';
} else{
  window.location = 'index.php?option=mycomponent&view=myview&Itemid=380&lang=en&sent=1'; 
} 

然后让我们将变量移出if并检查是否为false(如果返回的值等于false,这需要我们在下面对原始函数进行更新):

var ret = jQuery.urlParam('returnview');
var iid;
if(ret === false) {     
   window.location = 'index.php?option=mycomponent&view=myview&Itemid=380&lang=en&sent=1'; 
} else{
  iid = jQuery.urlParam('iid'); 
  window.location = 'index.php?option=mycomponent&view='+ret+'&Itemid='+iid+'&lang=en';  
} 

…最后,让我们修正你的原始函数:

jQuery.urlParam = function(name){
   var results = new RegExp('[''?&]' + name + '=([^&#]*)').exec(window.location.href);
   return (results && results[0] ? results[0] : false);
}

我还没有测试过,但我认为应该可以修复它

检查jQuery.urlParam('returnview')下的内容我很确定,如果value没有设置,你将得到undefined

Try jQuery.urlParam('returnview') === undefined

获取转义URL参数

根据函数是否返回真值来有条件地设置url参数:

var ret = jQuery.urlParam('returnview');
var iid = jQuery.urlParam('iid');
var view = ret || "myview";
var id = iid || "380";
window.location = 'index.php?option=mycomponent&view='+
                   view + '&Itemid=' + id + '&lang=en';

对于urlParam函数,您需要确保仅捕获参数本身,而不是整个"&abc=xyz"段。您只需在所需的部分周围添加括号来捕获它,然后进行第二个匹配(第一个索引)。在解引用匹配数组之前,检查它是否为空:

jQuery.urlParam = function(name){
    var re = RegExp('[''?&]' + name + '=([^&#]*)');
    var results = window.location.href.match(re);
    return results ? results[1] : null;
}