2015-06-19 46 views
1

我要插入一个电子邮件地址到我的分贝与Ajax调用。 这里谈到的问题,而是工作到背景,它刷新页面。

alert("yea");在成功的功能没有被达到

可能是什么问题

$(document).ready(function() { 
     $("#header-subscribe").click(function(){ 
     var str = $("#email").val();   
     if(validateEmail(str)) { 

     $.ajax({ 

     url: 'php/signupForm.php', 
     type: 'GET', 
     data: 'email='+str, 
     success: function(data) { 
     //called when successful 
     alert("yea"); 
     }, 
     error: function(e) { 
     //called when there is an error 
     //console.log(e.message); 
     } 

    }); 

形式:?

<form id="hero-subscribe" class="the-subscribe-form" > 
    <div class="input-group"> 
     <input type="email" class="form-control" placeholder="Enter Your Email" id="email"> 
     <span class="input-group-btn"> 
      <button class="btn btn-subscribe" id="header-subscribe" type="submit">subscribe</button> 
     </span> 
    </div> 
</form> 
+0

你不能阻止点击的默认操作。 –

回答

6

Ajax调用与刷新无关。你有一个提交按钮,提交按钮的目的是提交表单。

最简单的解决办法是不使用一个提交按钮:

type="button" 

然而,事件处理程序绑定到按钮的单击事件是不是好的做法。所以不是说,改变的类型,处理程序绑定到submit事件和prevent the default action(这是提交表单):

$("#hero-subscribe").submit(function(event) { 
    event.preventDefault(); 
    // ... 
}); 
1

event.preventDefault()表单动作,否则就像正常表单一样提交。

$("#header-subscribe").click(function(event){ 
    event.preventDefault(); //stop the default submit action 
4

您需要防止点击的默认操作...

$("#header-subscribe").click(function(event){ 
    event.preventDefault(); 
2

你应该绑定submit活动形式,并使用event.preventDefault()阻止事件的默认操作。

$("#hero-subscribe").submit(function(event) { 
    event.preventDefault(); 
    //Your code 
});