Javascript 如何使用 jquery $.post() 方法提交表单值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25881204/
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 use jquery $.post() method to submit form values
提问by Yolo
I have 1 main page with a form and another page to process the form value here are source codes of the 2 pages
我有 1 个带有表单的主页和另一个用于处理表单值的页面,这里是 2 个页面的源代码
Form Page:
表格页面:
<meta charset="UTF-8">
<title>Form Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="process.php" method="post" id="reg-form">
Username: <input type="text" id="username" name="username">
<br>
Password: <input type="password" id="password" name="password">
<br>
<button type="submit" id="submit-btn">Traditional Submit</button>
<button type="button" id="post-btn">$.Post Submit</button>
</form>
<script>
$("#post-btn").click(function(){
$.post("process.php",function(data){
alert(data);
});
});
</script>
Process Page:
流程页面:
<?php
$username=$_POST["username"];
$password=$_POST["password"];
echo "Username: ".$username;
echo "<br>";
echo "Password: ".$password;?>
if I click the "Traditional Submit" buttton, it works perfectly well.
如果我单击“传统提交”按钮,它运行良好。
but when I click the "$.Post Submit" button, I just keep getting error msg "Notice: Undefined Index ..."
但是当我点击“$.Post Submit”按钮时,我只是不断收到错误消息“注意:未定义索引......”
I can not figure out where the problem is, please kindly help check and fix, thanks in advance!
我无法弄清楚问题出在哪里,请帮助检查和修复,在此先感谢!
回答by nbrooks
You have to select and send the form data as well:
您还必须选择并发送表单数据:
$("#post-btn").click(function(){
$.post("process.php", $("#reg-form").serialize(), function(data) {
alert(data);
});
});
Take a look at the documentation for the jQuery serializemethod, which encodes the data from the form fields into a data-string to be sent to the server.
查看 jQueryserialize方法的文档,该方法将表单字段中的数据编码为要发送到服务器的数据字符串。
回答by John Robertson
Get the value of your textboxes using val()and store them in a variable. Pass those values through $.post. In using the $.Post Submit buttonyou can actually remove the form.
使用获取文本框的值val()并将它们存储在变量中。通过$.post. 在使用中,$.Post Submit button您实际上可以删除表单。
<script>
username = $("#username").val();
password = $("#password").val();
$("#post-btn").click(function(){
$.post("process.php", { username:username, password:password } ,function(data){
alert(data);
});
});
</script>
回答by MH2K9
Yor $.posthas no data. You need to pass the form data. You can use serialize()to post the form data. Try this
你$.post没有数据。您需要传递表单数据。您可以使用serialize()来发布表单数据。尝试这个
$("#post-btn").click(function(){
$.post("process.php", $('#reg-form').serialize() ,function(data){
alert(data);
});
});

