6

我正在尝试编写会弹出并说 Post 成功的 jquery 函数!如果没有,则 Post 不成功!我如何在输入一些 jquery 时使用 try catch?

@using (Html.BeginForm("Admin", "Home", "POST"))
{
<div class="well">
    <section>
        <br>
        <span style="font-weight:bold">Text File Destination:&#160;&#160;&#160;</span>
        <input type="text" name="txt_file_dest" value="@ViewBag.GetTextPath">
        <span style="color:black">&#160;&#160;&#160;Example:</span><span style="color:blue"> \\invincible\\chemistry$\\</span>
        <br>
        <br>
        <span style="font-weight:bold">SQL Connection String:</span>
        <input type="text" name="sql_Connection" value="@ViewBag.GetSqlConnection">
        <span style="color:black">&#160;&#160;&#160;Example:</span> <span style="color:blue"> Server=-</span>
        <br>
        <br>
        <button class="btn btn-success" type="submit" >Save Changes</button>
    </section>
</div>

}

4

5 回答 5

5

所以我想出了我的答案。仅供将来尝试此操作的任何人参考,以下是我所做的。我把它放在@using (Html.BeginForm("Admin", "Home", "POST")) 上面。@Andrew我确实尝试过你的,但我无法让它工作。感谢大家不厌其烦地帮助我。

<script language="javascript" type="text/javascript">
    $(function() {
       $("form").submit(function(e) {
          $.post($(this).attr("action"), // url 
  $(this).serialize(), // data
  function (data) { //success callback function
     alert("Edit successful");
  }).error(function () {
      alert('failure'); 
  });
             e.preventDefault();
          });
       });
</script>
于 2013-04-25T20:50:22.337 回答
1

您需要稍微更改 HtmlHelper BeginForm 声明,以便 id 属性将与元素一起呈现,如下所示:

@using (Html.BeginForm("Admin", "Home", FormMethod.Post, new { id = "well-form" }))

现在您可以在声明上方添加一个脚本,该脚本捕获并提交表单并处理响应(成功或错误)。

<script>
$(function() {
    // Find the form with id='well-form'
    $('#well-form').submit(function() {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function(result) {
               alert('Post was successful!');
            },
            error: function(result) {
               alert('Post was not successful!');
            }
        });
        // return false to cancel the form post
        // since javascript will perform it with ajax
        return false;
    });
});
</script>
于 2013-04-25T03:32:34.723 回答
0

你可以使用 Ajax 事件吗?比如 $.ajaxSuccess

http://api.jquery.com/category/ajax/global-ajax-event-handlers/

于 2013-04-25T03:41:20.990 回答
0
$.ajax({
  url: 'post.html',
  success: function(){
    alert('success');
  },
  error: function(){
    alert('failure');
  }
});
于 2013-04-25T01:41:49.757 回答
0

与 Sonu 的回答相辅相成,我发现关于这很难完成的类似问题,因为 HTML 表单提交没有回调,并且似乎建议ajax()在您想要回发确认表单提交时使用。

请参阅此Stackoverflow 链接

于 2013-04-25T03:25:09.133 回答