1

我正在开发一个单页 Web 应用程序。我添加了以下登录代码:

$('#loginLink, #registerLink')
   .click(function () {
      var $link = $(this);
      var href = $link.attr('data-href');
      $('#article').load(href);
   }
   return false;
});

这有效并使用以下 HTML 填充 #article 部分。请注意,我删除了这个问题的一些代码:

<form action="/User/Account/Login" method="post" novalidate="novalidate">
...
note there's client side validation on the page but I just don't show it here
...
<ol>
   <li>
      <input id="UserName" name="UserName" type="text" value="">
   </li>
</ol>
<input type="submit" value="Log in">
</form>

如果我单击提交,当表单出现时,它会向浏览器发送一个请求,并返回一个新页面。有没有办法我仍然可以保留提交操作(用于我页面上的客户端验证)但让提交结果带回一个页面,该页面再次显示在#article 部分?

4

2 回答 2

1

您正在寻找event.preventDefault()避免发送表单和重新加载整个网页。看到这个小提琴

于 2012-12-30T14:45:37.503 回答
1

有没有办法我仍然可以保留提交操作(用于我页面上的客户端验证)但让提交结果带回一个页面,该页面再次显示在#article 部分?

不确定我是否理解正确,但如果您想加载文章内容而不在提交时重新刷新页面,您可以绑定到submit事件并执行类似于以下的 ajax 调用:

on在下面的示例中使用了仅在 jQuery 1.7 中添加的示例。如果您使用的是 jQuery 1.6.x 或更低版本,则可以bind改用。

$("form").on("submit", function() {
    var $form = $(this);

    // if there are validation errors do not continue.
    if(!$form.valid()){
        return false;
    }

    // get the form data
    var myData = $form.serialize();

    // get the url to post to from the form's action attribute.
    var myUrl = $form.attr("action");

    // execute the post
    $.ajax({
        url: myUrl,
        data: myData 
        success: function(data) {
            // on success, write the returned article content into the article element
            $('#article').html(data);
        }
    });

    return false;
});​
于 2012-12-30T14:46:57.050 回答