2017-06-17 62 views
2

我有一个问题。我认为这是因为渲染,但我不知道,因为这个话题对我来说是新的。JavaScript提交按钮jQuery问题

好吧,我有一个简单的表格:

<form method="post" action="/send-mail"> 
<input type="text" name="msg" value=""> 
<input type="submit" value="send that fancy mail"> 
</form> 

现在我想赶上提交使用jQuery,如:

$('[type=submit]').submit(function(e) { 
    e.preventDefault(); 
    var formHtml = $(this).parent().html(); 

    $.ajax({ 
     ..all these options.., 
     beforeSend: function(xhr) { 
      $('form').html("sending mail"); 
     }, 
     success: function(data) { 
      $('form').html(formHtml); // I think here's the problem... 
     }  
    }); 
}); 

还行,代码工作真的很好。它做它应该做的事情。但是,如果我想发送第二个请求,则提交按钮不能按预期工作。它试图使用默认操作发送表单,尽管我预先设定了这一点 - 至少这就是我的想法。

我确实使用谷歌,但我甚至不知道如何解释我的问题。

希望有人能帮助我,非常感谢!

格尔茨

+2

提交事件应的形式,而不是按钮上放。这也有帮助,因为表单元素本身没有变化,因此事件监听器保持原位 –

回答

2

而不是的.html()你可以使用:

.clone(true):创建匹配的元素的深层副本。

.replaceWith():用提供的新内容替换匹配元素集合中的每个元素,并返回被删除的元素集合。

事件必须点击如果连接到提交按钮或提交如果附着的形式。

的片段:

$('[type=submit]').on('click', function (e) { 
 
    e.preventDefault(); 
 
    var formHtml = $(this).closest('form').clone(true); 
 
    $.ajax({ 
 
     dataType: "json", 
 
     url: 'https://api.github.com/repos/octocat/Hello-World', 
 
     beforeSend: function (xhr) { 
 
      $('form').html("sending mail"); 
 
     }, 
 
     success: function (data) { 
 
      console.log('Success'); 
 
      $('form').replaceWith(formHtml); // I think here's the problem... 
 
     } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<form method="post" action="/send-mail"> 
 
    <input type="text" name="msg" value=""> 
 
    <input type="submit" value="send that fancy mail"> 
 
</form>

+0

非常感谢你,你的代码解决了我的问题问题。 – PaddaelsM

0

使用$(document).on("click", "[type=submit]", function (e) {动态创建ekements代替$('[type=submit]').submit(function(e) {

0

使用<input type="button">代替<input type="submit">并添加onclick功能是这样的:

<input type="button" onclick="_submitForm()" value="send that fancy mail"> 

然后你的JS是:

function _submitForm(){ 
var formHtml = $(this).parent().html(); 

    $.ajax({ 
     ..all these options.., 
     beforeSend: function(xhr) { 
      $('form').html("sending mail"); 
     }, 
     success: function(data) { 
      $('form').html(formHtml); // I think here's the problem... 
     }  
    }); 
} 

我希望能解决你的问题。

+0

对不起,但我应该补充说,调用函数并没有解决我的问题:/ – PaddaelsM