Ajax表单提交,文件未提交 [英] Ajax form submission, files not getting submitted

查看:93
本文介绍了Ajax表单提交,文件未提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的Django表单实现AJAX表单提交。

I am trying to implement AJAX form submission for my Django forms.

文件在没有AJAX的情况下提交,因此服务器端的逻辑似乎正在工作。并且使用ajax,除文件之外的其余值都会被提交。

The files are getting submitted without AJAX, so the logic at the serverside seems to be working. and with ajax, the rest of the values except the files get submitted.

这是我正在实现的代码,

Here is the code that I am implementing,

(function() {
  // using jQuery
  function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }
  var csrftoken = getCookie('csrftoken');
  function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }
  $.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
    if (!csrfSafeMethod(settings.type)) {
      xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
  }
  });
})();



jquery



jquery

$('#save-form').live('submit', function(event) { // catch the form's submit event
  event.preventDefault();
  $.ajax({ // create an AJAX call...
      data: $(this).serialize(), // get the form data
      type: $(this).attr('method'), // GET or POST
      url: '/save/', // the file to call
      success: function(response) { // on success..
          $('#modalsave-form').html(response); // update the DIV
      }
  });
  return false;
});



HTML表格



HTML Form

<form class="form-horizontal" id="save-form" enctype="multipart/form-data" method="post" action="/save/">
    <div class="control-group">
        <label class="control-label" for="id_body">Write Something</label>
        <div class="controls">
          <textarea class="typeaheadfun" id="id_body" rows="3" cols="100" name="body" placeholder="Scribble Body" style="width: 455px;"></textarea>
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="id_media">Add a File</label>
        <div class="controls">
          <input type="file" name="media" id="id_media"/>
        </div>
    </div>
    <hr>
    <input class="btn btn-primary pull-right" type="submit" value="Post!" />
    <br>
    {% csrf_token %}
</form>


推荐答案

当您提交HTML表单时,它通常会发送表单的数据使用 GET POST 数据HTML标头到服务器。但是,当您需要有效地将二进制数据或附加文件发送到服务器时,HTML作为其中的一部分 spec 具有不同的发送此类数据的方法。 enctype 的属性< form> 标签指定浏览器使用哪种方法将数据发送到服务器。要发送文件, multipart / form-data 是广泛使用的编码方法。

When you submit an HTML form it usually sends form's data to the server using either GET or POST data HTML headers. When however you need to send binary data or attached file(s) to the server efficiently, HTML as part of it's spec has a different method for sending such data. enctype attribute of <form> tag specifies using which method should the browser send the data to the server. To send files, multipart/form-data is widely used encoding method.

当你尝试发送表格时没有ajax,浏览器使用 multipart / form-data 编码将文件数据发送到服务器,但是当您使用ajax提交表单时,请执行以下操作:

When you try to send form without ajax, browser sends file data to the server using multipart/form-data encoding however when you submit the form using ajax you do the following:

data: $(this).serialize()

该步骤不会像服务器期望数据一样对数据进行编码,因此您的ajax不起作用。

That step does not encode data the same way as server expects the data hence your ajax does not work.

要使其工作,而不是手动提交表单的数据,你应该使用ajax提交整个表单。手动操作很棘手,而且已经有插件可以做到这一点。一个这样的插件是 jQuery Form Plugin 。它允许使用ajax提交整个表单。以下是js代码,它可以让您了解如何将其与您的设置集成:

To make it work, instead of manually submitting form's data, you should submit the whole form using ajax. Doing it manually is tricky plus there are plugins which do that already. One such plugin is jQuery Form Plugin. It allows to submit the whole form using ajax. The following is js code which should give you an idea on how to integrate it with your setup:

$('#save-form').live('submit', function(event) {
    event.preventDefault();

    $(this).ajaxSubmit({
        url: '/save/', // the file to call
        success: function(response) {
            $('#modalsave-form').html(response);
        }
    });

    return false;
});

这篇关于Ajax表单提交,文件未提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆