如何使用 JavaScript 提交表单并重定向到 URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25989499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:21:13  来源:igfitidea点击:

How to submit form using JavaScript and redirect to a URL?

javascriptphpjqueryforms

提问by pap mooo

How to submit form using JavaScript and redirect to a URL ?

如何使用 JavaScript 提交表单并重定向到 URL?

<form name="f1" method="get" action="aaa.php">
    name : <input type="text" name="value_1" value=""/><br>
    age: <input type="text" name="value_2" value=""/>
    <input type="submit" name="submit" value="send"/>
</form>

please see image in this link:

请查看此链接中的图片:

http://image.ohozaa.com/i/4d0/zCzQIH.jpg

http://image.ohozaa.com/i/4d0/zCzQIH.jpg

after press submit button , i want to redirect page to www.example.com/aaa/robert/21

按提交按钮后,我想将页面重定向到 www.example.com/aaa/robert/21

How can i do that ?

我怎样才能做到这一点 ?

回答by ??c ?oàn Quang

Try this with html code

用 html 代码试试这个

<form name="f1" method="get" action="aaa.php">
name : <input type="text" id="value_1" name="value_1" value=""/><br>
age: <input type="text" id="value_2" name="value_2" value=""/>
<input type="button" name="submit" onclick="checkredirect()" value="send"/>

And javascript

和 javascript

<script type="text/javascript">
function checkredirect(){
    var value_1 = $('#value_1').val();
    var value_2 =  $('#value_2').val();
    window.location = 'http://www.example.com/'+value_1+'/'+value_2;
    return false;
}
</script>

Don't forget to add jQuery library

不要忘记添加jQuery库

回答by laruiss

Maybe something like this:

也许是这样的:

HTML:

HTML:

<form id="f1" class="js-redirect" method="get" action="aaa.php">
    name : <input type="text" name="value_1" id="value_1" value=""/><br>
    age: <input type="text" name="value_2" id="value_2" value=""/>
    <input type="submit" name="submit" value="send"/>
</form>

N.B.: nameattribute in formtags is deprecated, use idattribute. Input, selectand textareatags should have ids as well.

注:name在属性form标签已经过时,使用id属性。Inputselect并且textarea标签应该具有idS作为良好。

JS:

JS:

$('.js-redirect').on('submit', function() {
    var newUrl = this.action.replace('.php', '/' + $('#value_1').val() + '/' + $('#value_2').val());
    this.action = newUrl;
})

回答by Man Programmer

set header in php file

在 php 文件中设置标题

$dynamic = $_GET['value_1'];
$id =$_GET['value_2'];
header('location:www.example.com/aaa/'.$dynamic.'/'.$id);

回答by Harutyun Abgaryan

Try this function on click button

点击按钮试试这个功能

function myFunction() {
    document.getElementById("myForm").submit();
}