gpt4 book ai didi

javascript - 通过 AJAX 提交表单而不重新加载页面

转载 作者:数据小太阳 更新时间:2023-10-29 07:41:23 25 4
gpt4 key购买 nike

有没有什么方法可以在不重新加载页面的情况下将表单提交到服务器以获得 AJAX 响应。我可以使用提交按钮来做到这一点。但是当链接被点击时,我该如何做到这一点。

我开始了解一个 javascript 方法来做到这一点,

var form = document.getElementById('myForm');
form.submit();

但是上面的代码重新加载了页面。我开始知道我们可以用 jquery 做到这一点,但是怎么做呢?

请注意,我正在使用 Ruby on Rails 3.0.4 开发我的应用程序,并且我正在像这样使用 Rails AJAX。

<%= form_for @search, :remote => true, :url => request_path, :html => {:method => :get, :id => :my_form} do |f| %>

如有任何帮助,我们将不胜感激。

最佳答案

您可以使用 preventDefault() 事件对象的方法:

$('#myForm').submit(function(event){
event.preventDefault();
$.ajax({
...
});
})

If this method is called, the default action of the event will not be triggered.

关于javascript - 通过 AJAX 提交表单而不重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11882444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com