为什么"$ .ajax({"令人耳目一新?

not*_*tme 1 javascript php ajax jquery

我想通过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);
      }

    }); 
Run Code Online (Sandbox Code Playgroud)

表格:

<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>
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 6

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

最简单的解决方案是不使用提交按钮:

type="button"
Run Code Online (Sandbox Code Playgroud)

但是,将事件处理程序绑定到按钮的单击事件并不是一种好习惯.因此,而不是更改类型,将处理程序绑定到submit事件并阻止默认操作(提交表单):

$("#hero-subscribe").submit(function(event) {
    event.preventDefault();
    // ...
});
Run Code Online (Sandbox Code Playgroud)