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>
261313 次浏览

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

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

Http://api.jquery.com/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);
}
});

我觉得这肯定能行。

您还可以使用 。序列化()函数通过 jquery Ajax 发送数据。

i.e: data : $("#registerSubmit").serialize()

谢谢。

使用序列化方法:

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

医生: 序列化()

var username = $('#username').val();
var email= $('#email').val();
var password= $('#password').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);
}
});

You dont have to bother about anything else. jquery will handle the serialization etc. also you can append the submit query string parameter submit=1 into the data json object.

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