2015-04-15 94 views
1

我已经检查过这里,并没有这些解决方案在这里解决我的问题。 我似乎无法得到preventDefault()的工作。下面的代码:防止默认不起作用

的Jquery:

$("#changepassword").submit(function(event) { 
    event.preventDefault(); // stop normal form submission 
    $.ajax({ 
     url: "changePassword.php", 
     type: "POST", 
     data: $(this).serialize(), // you also need to send the form data 
     dataType: "html", 
     success: function(html) { 
      $("#s-window").append(html); 
     } 
    }); 
}); 

HTML:

<div id="s-window"> 
     <form id="changepassword" action="changePassword.php" method="POST"> 
      <input type="password" name="currentPassword" placeholder="Current Password"/> 
      <input type="password" name="newPassword" placeholder="New Password"/> 
      <input type="password" name="confirmPassword" placeholder="Confirm Password"/> 
      <input class="button" type="submit" value="Change Password" /> 
     </form> 
    </div> 

有我的conosle没有错误。 changePassword.php按照它应该的方式工作。但不是更新我的#s-window,而是将我重定向到changePassword.php页面

我该如何重新编码这个以使所有事情都发生在页面上?

+0

为什么不删除'如果你正在使用AJAX反正form'属性。 –

+0

主要是因为我不知道我在做什么。我可以做到这一点,如果它会工作?你有什么可以解释为什么我会做出这些改变? –

+0

看,你的代码反正通过ajax调用相同的php方法。所以'action'属性的形式是没用的。尝试从form标签中移除'action'和'method'。 –

回答

1

您需要等到文档准备就绪:

$(document).ready(function(){ 
    $("#changepassword").submit(function(event) { 
     event.preventDefault(); // stop normal form submission 
     $.ajax({ 
      url: "changePassword2.php", 
      type: "POST", 
      data: $(this).serialize(), // you also need to send the form data 
      dataType: "html", 
      success: function(html) { 
       $("#s-window").append(html); 
      } 
     }); 
    }); 
}); 
1

您可以尝试使用return false;这种方式,如果您有任何困惑在这里看到更多的event.preventDefault() vs. return false

$("#changepassword").submit(function(event) { 
    //event.preventDefault(); // stop normal form submission 
    return false; 
}); 
+0

这仍然将我重定向到changePassword.php脚本。这只是一个空白的白页。 –

0

在你的AJAX调用改变dataType: "html"dataType: "script"

+0

它没有区别。这两个是相同的。 – Blazemonger

+0

这是不同的,他使用提交功能,而我要求用'on' –

+0

http://api.jquery.com/submit说:“这种方法是'.on(”提交“,处理程序的快捷方式) '“ – Blazemonger

0

至少在IE浏览器,event是一个全局变量(根据Is 'event' a reserved word in JavaScript?)。这可能不是你的问题的原因,但尽管如此,改变你的命名可能是一个好主意。

+0

如果您认为这可能是问题,我可以将事件更改为e或其他东西? –

+1

试试吧。如果没有别的,它会更整洁。 'e'将是一个好名字。 – rusmus