2016-12-04 76 views
0

为什么在每个浏览器中此代码的行为不同?我应该改变什么来完成所有这些行为中的相同行为?在Firefox它是好的,它使用URL /some/path/?searchedText=sometext,在IE它当我点击inputButton,并在Chrome,因为它编码?这样的失败没有:/some/path/%3FsearchedText=sometext代替/some/path/?searchedText=sometext独立于浏览器的javascript

HTML

<input id="inputText" type="text" class="form-control" placeholder="Searched text"> <input id="inputButton" type='button' value='Search' class="btn" onclick="myFunction()"/>

的JavaScript

function myFunction() { 
var text = document.getElementById('inputText').value; 
var location = "some/path/?searchedText="; 
window.location.pathname = location + text; 
} 
+0

什么版本的IE? – 2016-12-04 10:09:21

+0

这是最新的版本11。 –

回答

1

您正在使用window.location.pathname这是伟大的方式,以避免明确地将起始(http://www.something.com)主机名,但它也把查询字符串作为路径,因此对其进行编码就可以避免通过manully构建每个URL部分,然后用window.location.href

function myFunction() { 
    var text = document.getElementById('inputText').value; 
    var protocol = window.location.protocol; 
    var hostname = window.location.hostname; 
    var url = protocol + '//' + hostname + "/some/path?searchedText=" + text; 
    window.location.href = url; 
} 
0

你可以使用属性search

window.location.search = '?searchedText=' + text; 
相关问题