友好的URL与GET请求表单

0 投票
2 回答
1090 浏览
提问于 2025-04-16 08:53

我有一个简单的HTML表单:

<form action="test/" method="get" accept-charset="utf-8">

    <input type="text" name="first" value="" id="first">
    <input type="text" name="second" value="" id="second">
    <input type="text" name="third" value="" id="third">

    <p><input type="submit" value="Continue &rarr;"></p>
</form>

当用户点击提交按钮时,我想得到一个友好的网址,像这样:

www.site.com/test/first/second/third

我该怎么做呢?

2 个回答

2
    <input type="text" name="first" value="" id="first">
    <input type="text" name="second" value="" id="second">
    <input type="text" name="third" value="" id="third">

    <p><input type="button" value="Continue &rarr;" onclick="submitFriendly();"></p>

<script type="text/javascript">
function submitFriendly() {
window.location.href = window.location.href + document.getElementById('first').value + '/' + document.getElementById('second').value + '/' + document.getElementById('third').value;
}
</script>

这个应该可以用。它并没有检查所有输入框是否都填好了。

3

用户在填写完表单并点击“继续”后会去哪里,取决于你在

标签中设置的action属性。目前你把它设置为test/

如果你希望他们最终到达test/<first_val>/<second_val>/<third_val>/,你可以使用一些JavaScript(就像pythonFoo的回答那样),或者在指向test/的视图中进行重定向,使用HttpResponseRedirect

def test_view(request):
  return HttpResponseRedirect('/test/%s/%s/%s/' % request.POST['first'],
                                                  request.POST['second'],
                                                  request.POST['third])

撰写回答