如何使用 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
How to submit form using JavaScript and redirect to a URL?
提问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.: name
attribute in form
tags is deprecated, use id
attribute. Input
, select
and textarea
tags should have id
s as well.
注:name
在属性form
标签已经过时,使用id
属性。Input
,select
并且textarea
标签应该具有id
S作为良好。
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();
}