1

我想要使​​用此代码处理的表单:

 //All form submissions should go through here.
 $(document).on('submit', 'form', function (x) {
     //x.preventDefault();  //commented out because it's not working
     $.ajax({
         url: $(this + '#formdestination').val(), //formdestination is a hidden field, showing where to submit the form
         type: 'post',
         dataType: 'json',
         data: $(this).serialize(),
         complete: function (xhr, status) {
            if (status === 'error' || !xhr.responseText) {
                window.location = '/broken/?err=Inconsolable%20onsubmit%20ajax%20error'; //i'd like the real error here, ideally
            } //end if
            else {
                loader($('#pagedestination').val()); 
                //loader is a function that animates the page as it loads new content.
                //#pagedestination is a hidden field that stores where the page should go when it's done.
                //Yes, I know formdestination and pagedestination could be handled with the form or the backend.  There are reasons that do not matter much here.
            } //end else
        } //end complete function

    });

    return false;
});

我有几个问题。

1.) 当一个表单被提交时,它会调用这个函数。它不调用加载程序,或者如果调用,它会被控制器的重定向覆盖。提交表单时,我需要防止通用提交。.preventDefault() 无法正常工作(见下文)。

2.)(远不如#1重要)如果ajax失败,我想得到合法的错误。如何?

On .preventDefault() - 当我尝试它时,我得到这个错误:Uncaught SyntaxError: Unexpected identifier

谢谢你的帮助。

4

2 回答 2

1
$(document).on('submit', 'form', function (x) {
    x.preventDefault();  //x must be inside the anonymous function
    $.ajax({
于 2013-03-01T17:03:01.203 回答
1

你得到的例外来自其他地方,请访问这个小提琴:http: //jsfiddle.net/DgRLa/

它有这个代码:

$(document).on('click', '.test', function (x) {
    x.preventDefault();  //commented out because it's not working

    $.ajax({
         url: "test.php", //formdestination is a hidden field, showing where to submit the form
         type: 'post',
         dataType: 'json',
         data: $(this).serialize(),
         complete: function (xhr, status) {
             console.log("hi");
         } 
    }).fail(function () {
        alert("error");
    });
});

当您单击“clickme”元素时,您将同时获得 console.log 和警报。

使用“成功”回调而不是“完成”回调,并使用 deferred .fail 来捕获错误,尝试这样的事情:

$(document).on('submit', 'form', function (x) {
     x.preventDefault();  //commented out because it's not working
     var url = $(this).attr("action");     

     $.ajax({
         url: url , // Use the form action attribute instead of a hidden field
         type: 'post',
         dataType: 'json',
         data: $(this).serialize(),
         success: function (data) {
             loader($('#pagedestination').val()); 
         } 
    }).fail(function (error) {
         // error has all sorts of fun stuff
    });

    // return false; Dont return false, preventDefault is enough
});

PS:您提到加载器将用户发送到不同的页面,如果您要重定向页面,是否有理由使用 ajax 提交表单?

于 2013-03-01T17:15:45.083 回答