烧瓶jsonify没有显示在HTML(ajax)

时间:2018-05-15 01:46:01

标签: jquery json ajax flask

我在同一个html页面上有3个表单,其中一个是上传csv文件。此表单正确上传(在服务器上接收)但来自服务器的结果响应不会显示在html中 - 而是仅作为原始/已解析对象在浏览器中显示:click for screenshot of browser

这是html:

    <div class="container">
       <div class="">
     <div class="jumbotron" style="overflow-x:scroll; white-space: nowrap;">
        <form id="upload" name="form_upload" enctype="multipart/form-data" method="post" action="/uploadcsv">
           <div class="col">
              <input type="file" name="data_file" />
              <button id="btn_upload" type="submit" class="btn btn-primary" >Upload</button>
           </div>
        </form>

这就是它应该显示的地方:

<div class="table table-hover">
   <div id="firsthead">
   </div>
</div>

以下是表单的JavaScript:

   <script>
  $(document).ready(function(){
    var upload_data = new FormData($('#upload')[0]);
      $("#button").click(function(e){
        e.preventDefault();
          $.ajax({
            data: upload_data,
            type : 'POST',
            url : '/uploadcsv',
            success: function(d){
              $("#firsthead").html(d.head_table);
          }
        });
      });
  });</script>

这是烧瓶应用程序:

@app.route('/uploadcsv', methods=["POST"])
def uploadcsv():
    print('hello uploadcsv')
    print('type (request)', type (request.files['data_file']))
    f = request.files['data_file']
    if not f:
        return "No file"
    df = pd.read_csv(f)
    print('df.head(): ', df.head())
    df.to_csv('../data/df.csv')
    head1 = print_head(df)
    print('the head', head1)
    columns = list(df.columns)
    return jsonify(head_table = head1)

我无法理解为什么这不起作用 - 因为我在同一页面中的情况几乎相同,它确实有效。唯一的区别是好的表单没有上传文件。

感谢您的任何指示!

2 个答案:

答案 0 :(得分:0)

尝试设置&#34; 缓存,processData,contentType &#34;到 false

&#13;
&#13;
<script>
  $(document).ready(function() {
    // submit event
    $("#upload").submit(function(e) {
      e.preventDefault();
      var upload_data = new FormData($('#upload')[0]);
      $.ajax({
        data: upload_data,
        type: 'POST',
        url: $(this).attr('action'),

        // Options to tell JQuery not to process data or worry about content-type
        cache: false,
        processData: false,
        contentType: false,

        success: function(d) {
          $("#firsthead").html(d.head_table);
        }
      });
    });
  });
</script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我怀疑发生的事情是表单的默认行为未被禁用,在提交时,它会重定向到结果

尝试显式调用表单submit和preventDefault

<script>

    $("#upload").submit(function(e) {
        e.preventDefault();
    });

      $(document).ready(function(){
        var upload_data = new FormData($('#upload')[0]);
          $("#button").click(function(){
              $.ajax({
                data: upload_data,
                type : 'POST',
                url : '/uploadcsv',
                success: function(d){
                  $("#firsthead").html(d.head_table);
              }
            });
          });
      });</script>