jQuery – 获取Ajax POST的表单值

我想通过AJAX张贴表单值到一个PHP文件。 如何收集我的表单值以发送“data”参数?

$.ajax({ type: "POST", data: "submit=1&username="+username+"&email="+email+"&password="+password+"&passconf="+passconf, url: "http://rt.ja.com/includes/register.php", success: function(data) { //alert(data); $('#userError').html(data); $("#userError").html(userChar); $("#userError").html(userTaken); } }); 

HTML:

 <div id="border"> <form action="/" id="registerSubmit"> <div id="userError"></div> Username: <input type="text" name="username" id="username" size="10"/><br> <div id="emailError" ></div> Email: <input type="text" name="email" size="10" id="email"/><br> <div id="passError" ></div> Password: <input type="password" name="password" size="10" id="password"/><br> <div id="passConfError" ></div> Confirm Password: <input type="password" name="passconf" size="10" id="passconf"/><br> <input type="submit" name="submit" value="Register" /> </form> </div> 

使用序列化方法:

 $.ajax({ ... data: $("#registerSubmit").serialize(), ... }) 

文档: serialize()

 $("#registerSubmit").serialize() // returns all the data in your form $.ajax({ type: "POST", url: 'your url', data: $("#registerSubmit").serialize(), success: function() { //success message mybe... } }); 

您可以使用val函数从input中收集数据:

 jQuery("#myInput1").val(); 

http://api.jquery.com/val/

 var data={ userName: $('#userName').val(), email: $('#email').val(), //add other properties similarly } 

 $.ajax({ type: "POST", url: "http://rt.ja.com/includes/register.php?submit=1", data: data success: function(html) { //alert(html); $('#userError').html(html); $("#userError").html(userChar); $("#userError").html(userTaken); } }); 

你不必担心其他事情。 jquery将处理序列化等,您也可以将提交查询字符​​串参数submit = 1附加到数据json对象中。

 var username = $('#username').val(); var email= $('#email').val(); var password= $('#password').val(); 

试试这个代码。

 $.ajax({ type: "POST", url: "http://rt.ja.com/includes/register.php?submit=1", data: "username="+username+"&email="+email+"&password="+password+"&passconf="+passconf, success: function(html) { //alert(html); $('#userError').html(html); $("#userError").html(userChar); $("#userError").html(userTaken); } }); 

我认为这将工作肯定..

你也可以使用.serialize()函数通过jQuery Ajax发送数据。

 ie: data : $("#registerSubmit").serialize() 

谢谢。