【问题标题】:Django: Ajax not receiving data from server responseDjango:Ajax 未从服务器响应接收数据
【发布时间】:2018-10-16 07:31:25
【问题描述】:

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

目前,我的 views.py 文件中有两个函数。一个处理上传文件(home),另一个处理调用python脚本并处理文件(句柄)。我这样分开它的原因是因为我想按顺序填充一个 HTML 表,因为 python 脚本与上传的文件一起工作。

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

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 出了什么问题,但是您绝对不能使用这样的全局变量来保持请求之间的状态。

标签: javascript python jquery ajax django


【解决方案1】:

我给你解释了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")
        }
    });
});

【讨论】:

  • 首先,感谢您这么快的回答。其次,我不确定为什么 field_example 变量没有在任何地方使用。另外,我将如何通过 Json 响应将数据发送回 ajax 函数?在这个例子中,没有任何东西被发回。出于测试目的,我尝试通过执行以下操作将文件名发回: data = {} data['Name'] = fileName(uploaded_file) #function I defined return JsonResponse(data)
  • 我在 formData 变量 js 代码中发送 field_example 字段。如果您需要按值发送自定义字段,请执行以下操作: $.ajax({ url: "{% url 'handle' %}", type: 'GET', data: { "example_field": "value_example", "example_field2 ": "value_example2", }, ...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-24
  • 2018-02-04
  • 1970-01-01
  • 2020-09-17
  • 1970-01-01
  • 2020-04-14
  • 2019-08-13
相关资源
最近更新 更多