-1

我有这个功能(让我的表单与 ajax 一起工作):

$(function() {
   $('#restore_form').ajaxForm({
   beforeSubmit: ShowRequest,
   success: SubmitSuccesful,
   error: AjaxError
   });
});

function ShowRequest(formData, jqForm, options) {
   var queryString = $.param(formData);
   alert('BeforeSend method: \n\nAbout to submit: \n\n' + queryString);
   return true;
}

function AjaxError() {
   alert("An AJAX error occured.");
}

function SubmitSuccesful(responseText, statusText) {
   alert("SuccesMethod:\n\n" + responseText);
}

我的表单(django 表单)只包含一个文件上传字段。我还想检查验证,为此我有这个功能:

function TestFileType( fileName, fileTypes ) {
   if (!fileName) {
      alert("please enter a file");
      return false; 
   }
   dots = fileName.split(".")
   fileType = "." + dots[dots.length-1];
   if(fileTypes.join(".").indexOf(fileType) != -1){
      alert('That file is OK!') ;
      return true;
   }
   else 
   { 
      alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
      return false;
   }
}

现在当我尝试在第一个函数中使用验证函数(TestFileType)时,它不起作用。他们两个单独工作。例如,如果我在提交按钮的 onclick 中编写以下行,它可以工作:

onclick="TestFileType(this.form.file.value, ['tar.gz']);"

我还想在成功功能中显示一个隐藏的 div,而不是提醒用户:我有:

我想在成功功能中做:

 $('.response').html(responseText);
 $('.response').show();

编辑:这是我的模板:

<form id="restore_form" enctype="multipart/form-data" method="POST" action="restore/">
        {{ form.non_field_errors }}
        {{ form.as_p }}
        {{ form.file.errors }}
        <p id="sendwrapper"><input type="submit" value="{% trans "Send" %}" id="submitButton" style="margin-bottom:10px; cursor:pointer; background-color:#F90;"/></p>            
 </form>
 <div class="response" style="display: none;"></div>

但它不起作用!似乎只有警报在此功能中有效。你能帮我么?真的谢谢 :)

4

1 回答 1

1

我过去曾尝试使用 AjaxForm 插件,发现除非您有非常具体的原因使用它,否则在没有插件的情况下编写 ajax 表单提交代码通常更容易。这是我使用没有插件的 Jquery 创建的以前的 jquery ajaxform 的简化/注释版本:

 $('form').submit(function(event) {
    var form = $(this);

    // creates a javascript object of the form data
    // which can be used to validate form data
    var formArray = form.serializeArray();
    // (validate whatever values in formArray you need to check here);

    if (form_is_valid) {
        var formData = form.serialize(); // a URL-encoded version of the form data for the ajax submission
        $.ajax({
            type: "POST",
            url: someUrl,
            data: formData,
            success: function(data) {
                // update success message boxes here
            }
        });
    } else {
        // update client-side validation error message boxes
    }
    event.preventDefault(); // prevent the form from actually navigating to the action page
});

希望这会有所帮助,我发现该插件有时很有用,但是我通常发现这会导致更容易理解代码并避免使用插件..

于 2012-11-11T06:57:29.393 回答