2013-02-25 89 views
0

我想參數添加到URL,對於我有2個文本框和一個按鈕,我想不出我在哪裏卡住,無法添加參數以URL
這裏是我的代碼:
無法添加參數,URL

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; 
    } 
} 
+0

哪些具體問題? – 2013-02-25 06:17:43

+0

你有什麼錯誤(如果有的話)?這不起作用的方式? – Keppil 2013-02-25 06:17:53

+0

這是一個JavaScript問題,不解決Java,HTML或JSP問題= \ – 2013-02-25 06:18:24

回答

1

從以上評論:

我測試了你的代碼併爲我工作(如果頁面以html,jsp或.something結尾)。這是使用Chrome v25進行測試的。

後來,我測試了IE9,並且在爲本地執行的頁面啓用腳本執行後,它工作。當您進入IE時會彈出一條消息。在IE9中,它出現在底部,說Internet Explorer限制此網頁運行腳本或ActiveX控件。,並在右側有這個選項允許阻止的內容。

對於IE向後兼容性,似乎應該替換james emanon's answer中所述的d[1].trim()

作爲建議,至少使用兩個瀏覽器來測試您的網頁。是的,我強烈建議在IE上進行測試,因爲它會給你一個好的(?)反饋,以便對腳本錯誤非常敏感(它會產生很多Chrome和Firefox爲你覆蓋的錯誤)。

1

當在IE中運行這個(我在IE 10測試這一點),你需要允許BLO爲了使JavaScript運行,需要添加內容。否則,JavaScript將不被允許運行。 Luiggi Mendoza對IE 9提出了相同的建議。

值得注意的是,在Chrome和FireFox中,沒有任何允許JavaScript運行的用戶確認,這項工作正常。

1

IE不喜歡「.trim()」。我使用IE8 compat模式在IE8中測試,並且由於修剪,您的代碼無法工作。雖然我想IE9是好的(正如Luigi的確認所指出的那樣)。

使用這樣的事情,而不是:

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

你可以得到它周圍的東西,如:

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

然後就打電話給它,並通過您的PARAM

if (stripWhiteSpace(b)) 
+0

thankx :)你也對我的回答有所貢獻 – lata 2013-02-25 07:52:06

1

我支持@ rhughes的回答。但是,如果你在IE8中測試這段代碼(我正在使用這個和你的代碼不工作)和下面,HTML修剪()不會工作。正如你在三個地方修剪(),你必須使用以下內容。

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

,或者你可以更伊斯利使用jQuery修剪()

$.trim() 

refer 1

refer 2