1

我不想使用后面的代码来使用查询字符串进行重定向,因为将使用所见即所得编辑器来执行此操作。提交后,希望它重定向到http://abc.somedomainname.com?first=var1&last=var2

姓名

专家请建议我如何能够使用 javascript 或 jquery 使用查询字符串进行重定向。请写详细信息,因为我在这方面是全新的。

4

1 回答 1

0

第1步:将两个方法放入<HEAD></HEAD>

<script type="text/javascript" language="javascript">
// return the value of a parameter based on the name you pass in
function getParameterByName(name) { 
    // use regular expression to replace [ with \[, and replace
    //   ] with \], you get this if you
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

    // make a new regex that strips out the querystring parameters
    // the [\\?&] looks for the beginning ? or & characters,
    // then the name of the parameter (you passed it in to the method)
    // then the "=([^&#]*)" is looking for = followed by any character
    // except & or #. Because there are parentheses around this part
    // it will remember the match in a match group.
    var regexS = "[\\?&]" + name + "=([^&#]*)"; 

    // this converts the regular expression string into a RegExp object
    var regex = new RegExp(regexS); 

    // execute the regular expression against the URL
    var results = regex.exec(window.location.search); 
    if(results == null) {
        // it didn't find the parameter you passed in
        return ""; 
    } else {
       // we got a match! The value of your parameter is in the 
       // results array (parentheses in the regexS above told the
       // regex to store it there. We do a quick replace at the end
       // to convert the + character to a space, because it is URLEncoded
       return decodeURIComponent(results[1].replace(/\+/g, " ")); 
    }
}

// call this method to do the redirect
function redirectBasedOnParameters() {
    // read the value of the parameter named 'first'
    var var1 = getParameterByName('first');

    // read the value of the parameter named 'last'
    var var2 = getParameterByName('last');

    // redirect the browser
    window.location = "http://abc.somedomainname.com?first=" + var1 + "&last="+ var2

}
</script>

第 2 步:使用Body.onLoad事件强制触发 JavaScript

将脚本放入网页<head></head>标签后(见下文)。然后你可以强制脚本在 body 加载时执行,如下所示:

<html>
<head>
<script type="text/javascript">
  // put the JavaScript code mentioned above inside here 
</script>
</head>

<body onload="redirectBasedOnParameters()">
    <h1>Hello World!</h1>
</body>
</html> 
于 2012-04-26T00:17:06.847 回答