无法向url添加参数

时间:2013-02-25 06:16:07

标签: javascript

我想将参数添加到网址,因为我有2个文本框和一个按钮,我无法弄清楚我在哪里卡住并且无法将参数添加到网址
这是我的代码:

HTML:

Param Name: <input id="tbAddParam" type="text" /><br>
Param Value: <input id="tbAddParamValue" type="text" /><br>
<input onclick="javascript:AddParamter();" value="Add" type="button" />

JavaScript:

function AddParamter() {
    var new_url = AddUrlParameter(window.location.href, document.getElementById('tbAddParam').value, document.getElementById('tbAddParamValue').value);
    window.location.href = new_url;
}

function AddUrlParameter(a, b, c) {
    if (b.trim() == "") {
        alert("Parameter name should not be empty.");
        return a;
    }
    if (c.trim() == "") {
        alert("Parameter value should not be empty.");
        return a;
    }
    if (a.indexOf("?") == -1) {
        return a + "?" + b + "=" + c;
    }
    var d = a.split("?");
    if (d.length >= 2) {
        if (d[1].trim() == "") {
            return d[0] + "?" + b + "=" + c;
        }
        var e = d[1].split(/[&;]/g);
        for (var f = 0; f < e.length; f++) {
            var g = e[f]; var h = g.split("=");
            if (h.length >= 2) {
                if (h[0] == b) {
                    alert("Url Parameter with provided name already exists! Try Updating that Url Parameter.");
                    return a;
                }
            }
        }
        return a + "&" + b + "=" + c;
    }
}

4 个答案:

答案 0 :(得分:1)

在IE中运行时(我在IE 10中对此进行了测试),您需要允许阻止的内容才能运行JavaScript。否则,将不允许JavaScript运行。 Luiggi Mendoza对IE 9提出了同样的建议。

值得注意的是,这在Chrome和FireFox中运行良好,没有任何用户确认允许JavaScript运行。

答案 1 :(得分:1)

IE不喜欢“.trim()”。我在IE8中使用IE8 compat模式进行了测试,并且由于修剪,您的代码无法正常工作。虽然我认为IE9很好(正如路易吉确认的那样)。

使用类似的东西:

strReplace=str.replace(/^\s+/,'').replace(/\s+$/,''); 

你可以通过以下方式解决这个问题:

function stripWhiteSpace(arg){
   if(arg.replace(/^\s+/,'').replace(/\s+$/,'') == ""){
      return true;
   }
}

然后只需调用它并传递你的参数

if (stripWhiteSpace(b))

答案 2 :(得分:1)

来自上述评论:

我已经测试了你的代码并且适用于我(如果页面以html,jsp或.something结尾)。这是使用Chrome v25测试的。

后来,我在IE9上进行了测试,它在为本地执行页面启用脚本执行后起作用。当您进入IE时会弹出一条消息。在IE9中,它显示在底部,表示 Internet Explorer限制此网页运行脚本或ActiveX控件。并且右侧是此选项允许阻止的内容。

对于IE向后兼容性,您似乎应该按照james emanon's answer中的说明替换d[1].trim()

作为建议,请使用至少两个浏览器来测试您的网页。是的,我强烈建议在IE上进行测试,因为它会为您提供良好的(?)反馈,因为它们对脚本错误非常敏感(Chrome和Firefox会为您提供很多错误)。

答案 3 :(得分:1)

我支持@ rhughes的回答。但是,如果您在IE8中测试此代码(我使用此代码并且您的代码无法正常工作)及以下内容,则HTML trim()将无效。由于你在3个地方有trim(),你必须使用以下内容。

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

或者您可以更轻松地使用jQuery trim()

$.trim()

refer 1

refer 2

相关问题