Skip to main content
 首页 » 编程设计

javascript之Django:Ajax 没有从服务器响应接收数据

2024年08月16日42tuyile006

我是 Django 的新手,我正在尝试弄清楚如何在不重新加载页面的情况下动态添加来自 python 脚本的内容。

目前,我的 views.py 文件中有两个函数。一个负责上传文件 (home),另一个负责调用 python 脚本和处理文件 (handle)。我这样分开它的原因是因为我想在 python 脚本处理上传的文件时顺序填充一个 HTML 表。

但是,我的 ajax 函数没有从 handle 函数的 http 响应中接收到任何数据,我不确定为什么。 既没有调用成功函数也没有调用错误函数。这真的很奇怪,因为 views.py 中 handle 函数中的 print 语句成功打印了数据。

Views.py

i=0 
uploaded_file = None 
 
 
def home(request): 
 
    if (request.method == 'POST'): 
        file_form = UploadFileForm(request.POST, request.FILES) 
        if file_form.is_valid(): 
            global uploaded_file 
            uploaded_file = request.FILES['file'] 
            print(uploaded_file) 
    else: 
        file_form = UploadFileForm() 
 
    return render(request, 'personal/home.html', {'form': file_form}) 
 
 
 
def handle(request): 
 
    # TODO make ajax wait for a response from 'home' 
    # so I don't have to wait for 1 second   
    time.sleep(1) 
    data = {} 
    data['Name'] = fileName(uploaded_file) 
    if(request.is_ajax()): 
        print(data)        # prints succesfully 
    return HttpResponse(json.dumps(data),  
content_type="application/json") 

home.html

        <script type = "text/javascript" language = "javascript"> 
 
        function post_tables(data) { 
            alert(data) 
        } 
 
 
         $(document).ready(function(post_tables) { 
            $("#upload").click(function(event){ 
               $.ajax( { 
                  contentType: "application/json; charset=utf-8", 
                  dataType: "json", 
                  type: "get", 
                  url:'/handler', 
                  success: function(data) { 
                     console.log("over here") 
                     post_tables(data) 
                  }, 
                  error: function(data) { 
                      console.log("down here") 
                      post_tables("error being thrown") 
                  } 
               }); 
            }); 
         }); 
        </script> 

urls.py

urlpatterns = [ 
    path(r'', views.home, name='home'), 
    path(r'handler', views.handle, name='handle'), 
] 

请您参考如下方法:

我给你解释了ajax django的整个过程。也许你的问题会得到解决。祝你好运。

views.py

def handle(request): 
    if request.method == 'POST': 
        data = request.POST 
        field_example = data.get('field_example') 
 
        return JsonResponse(data) 
    else: 
        data = request.GET 
        field_example = data.get('field_example') 
        return JsonResponse(data) 

home.html

<form id="upload"> 
   {% csrf_token %} 
   <input type="text" name=field_example> 
   . 
   . 
   . 
</form> 

urls.py

urlpatterns = [ 
    path(r'', views.home, name='home'), 
    path(r'handler/', views.handle, name='handle'), 
] 

home.html中的js代码:

$("#upload").submit(function (e) { 
    e.preventDefault(); 
    var formData = new FormData(this); 
 
    $.ajax({ 
        url: "{% url 'handle' %}", 
 
        type: 'GET', 
        data: formData, 
        cache: false, 
        contentType: false, 
        processData: false, 
        success: function (data) { 
            console.log("over here") 
            post_tables(data) 
        }, 
        error: function (data) { 
            console.log("down here") 
            post_tables("error being thrown") 
        } 
    }); 
});