2012-12-19 93 views
1

我想通过jQuery ajax发送post变量到php自己的文档,但发送后,后置变量没有设置。发送post变量通过jquery(ajax)到php自己文档

代码:

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> 
+0

看起来你正在提交表单,那么为什么要使用ajax? – adeneo

+0

我怎么能没有Ajax? – user1551211

+0

通常的方式,通过提交表单与适当的操作和方法设置。 – adeneo

回答

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>

确保窗体必须设置操作。

+0

终于我这样做了,但我好奇,为什么我不能用ajax做... – user1551211

+0

因为你实际上没有提交表单。 –

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提交pervent形式!

您可以通过在按钮单击事件结束时返回false来做到这一点。或者通过使用事件对象e的方法e.preventDefault();

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

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