2012-12-19 97 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提交!