如何创建将用户发送到他们输入的路径的表单?

时间:2013-09-11 16:32:41

标签: html forms

我想在页面上有一个表单,要求用户输入一个值。点击“提交”按钮后,我希望将该值放在URL中,并将用户带到该页面。例如 - 如果用户输入:

this-is-what-the-user-enters

然后点击“提交”,他们的浏览器就会转到此页面:

http://my-website.com/this-is-what-the-users-enters

我确信这很简单,但我在其他地方找到的解决方案最终都包括“?”在生成的URL字符串中。

这是我尝试过的:

<script> 
function process() {
    var url="http://name.com/" + document.getElementById("url").value; 
    location.href=url; return false; 
} 
</script>

然后在HTML中添加一个表单:

<form onSubmit="return process();">
    URL: <input type="text" name="url" id="url"> <input type="submit" value="go">
</form>

从表单中获取值,但它增加了一个?到结果URL。

2 个答案:

答案 0 :(得分:1)

这很简单

<input id="url"/>
<input type="button" onclick="document.location='http://my-website.com/' + document.getElementById('url').value" value="Go!"/>

答案 1 :(得分:1)

从广义上讲,有两种方法可以解决这个问题。

  1. 在您的服务器上写一些内容,将用户重定向到表单中输入的路径。

  2. 使用JavaScript将window.location.pathname设置为用户输入的值,例如:

    <form action="#" method="GET" onsubmit="window.location.pathname = this.path.value; return false;">
        <label for="url">URL:</label> <input id="url" name="path" type="text"> <input type="submit">
    </form>
    
  3. (在实际网站中,您可能不会在onsubmit属性中包含JavaScript,但对于像这样的小事,它实际上可能是最好的方法。)