通过jquery(ajax)将post变量发送到php自己的文档

时间:2012-12-19 09:26:01

标签: php jquery ajax

我正在尝试通过jQuery ajax将post变量发送到php自己的文档,但是在发送之后,post vars没有设置。

代码:

    if(isset($_POST['email']) && isset($_POST['pass'])){

     do something
    }
<form id="form_login_pv">

Email: <input type="text" name="email" id="email"><br>
Password: <input type="password" name="pass" id="pass">

<div class="send_login_button_pv">Login</div>

</form>

<script type="text/javascript">

$('.send_login_button_pv').click(function(e){

  $.ajax({
    type: "POST",
    url: "index.php",
    data:$('#form_login_pv').serialize(),
    success: function(response){
                alert("mensaje enviado");

        }

});
});     

</script>

2 个答案:

答案 0 :(得分:0)

为什么不尝试使用表单提交jquery函数。

if(isset($_POST['email']) && isset($_POST['pass']))
{
    //do something
}

<form id="form_login_pv" action="<?php echo $_SERVER['PHP_SELF'] ?>">
Email: <input type="text" name="email" id="email">
Password: <input type="password" name="pass" id="pass"> <button type="submit" class="send_login_button_pv">Login</button> </form> <script type="text/javascript"> $('.send_login_button_pv').click(function(e) { e.preventDefault(); // just to make sure it wont perform other action $("#form_login_pv").submit(function(){ //afte server response code goes here }); }); </script>

确保表单必须设置操作。

答案 1 :(得分:0)

$.ajax({
    type: "POST",
    url: "index.php",
    data:$('#form_login_pv').serialize(),
    success: function(response){
        alert("mensaje enviado");
    }

});

在jQuery ready事件中尝试:

//you can also use an <input type="submit" value="login" /> instead ofusing a button!
$("#button_id").on("click",function(e){
    $("#form_login_pv").submit();
    return e.preventDefault();
});    

$("#form_login_pv").submit(function(e) {
    var email = $('input[name=email]').val();
    var pass = $('input[name=pass]').val();

    // validate given values here
    // if bad value detected, output error and return false;

    if(!email.test(YOUR REGEX HERE)) {
        $('#error-message').text('Wrong E-Mail Format!');
        return false;
    }
    if(pass.length<6) {
        $('#error-message').text('Password to short! At least 6 Characters!');
        return false;
    }
    $.ajax({
        type: "POST",
        url: "index.php",
        data: {
            email: email,
            pass: pass,
        },
        success: function(response){
            alert("mensaje enviado");
        }
    });
    return e.preventDefault();
});

并且不要忘记通过HTTP Post提交表单!

您可以通过在按钮点击事件结束时返回false来执行此操作。

或者使用事件对象e的方法,e.preventDefault();

我建议返回e.preventDefault();在点击功能结束时!

在通过ajax提交之前,您还可以检查给定的变量是否为空或使用javascript验证它们!

相关问题