1

我需要在我的表单中使用 ajax。但似乎 $.ajax 的成功功能,不支持文件。现在我想知道如何使用ajax,当我想要一些时间返回表单(何时无效)和一些时间返回流到客户端进行下载(当表单有效时)。我已经完成了谷歌搜索,似乎使用 $.get 它可能会起作用。但我有表格,我必须使用帖子。任何人都可以帮我解决办法吗?多谢。

在下面的函数中,流不起作用。

$('#sendButton').click(function(e) {
        e.preventDefault();
        var temp = $("#mainForm").serialize();
        $.ajax({
            type: "POST",
            data: temp,
            url: 'main/',
            success: function(data) {                
               ...
            }
        });
    });

我的意见.py:

def mainFunc(request):
    if request.is_ajax():
         form = mainForm(request.POST)
         if request.method == 'POST':
             if form.is_valid():
                 result = ""               
                 string_to_return = webservice._result
                 file_to_send = ContentFile(string_to_return)
                 response = HttpResponse(file_to_send,'application/x-gzip')
                 response['Content-Length'] = file_to_send.size
                 response['Content-Disposition'] = 'attachment;                  filename="somefile.tar.gz"'
                 return response
          else:
               form = mainForm()
          return render_to_response('main.html', RequestContext(request, {'form':form}))
     else:
          return render_to_response("ajax.html", {}, context_instance=RequestContext(request))
4

1 回答 1

1

您仍然无法将文件返回到 ajax 请求。答案自昨天以来没有改变

可以做的是返回下载的 url 并重定向用户或弹出打开一个新窗口/选项卡。像这样

$('#sendButton').click(function(e) {
    e.preventDefault();
    var temp = $("#mainForm").serialize();
    $.ajax({
        type: "POST",
        data: temp,
        url: 'main/',
        success: function(data) {
           # Option 1 - redirect
           window.location = data;
           # Option 2 - new window
           window.open(data, '_blank');
           window.focus();
        }
    });
});
于 2012-12-02T09:13:24.233 回答