使用jquery检查POST是否成功

时间:2013-04-25 01:40:34

标签: html asp.net-mvc html5 jquery

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

@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>

}

5 个答案:

答案 0 :(得分:3)

所以我想出了答案。只是为了将来参考尝试这个的任何人,下面是我做的。我把它放在@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>

答案 1 :(得分: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>

答案 2 :(得分:0)

$.ajax({
  url: 'post.html',
  success: function(){
    alert('success');
  },
  error: function(){
    alert('failure');
  }
});

答案 3 :(得分:0)

与Sonu的答案相比,我发现类似的问题很难实现,因为HTML表单提交没有回调,并且当你想要对表单提交的回发确认时,似乎建议使用ajax()

请参阅此Stackoverflow Link

答案 4 :(得分:0)

你能使用Ajax事件吗?例如$ .ajaxSuccess

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