首页 > 解决方案 > Django AJAX 返回 undefined 而不是变量

问题描述

所以我有一个简单的 Django 脚本,我在网上找到了一个运行 Python 脚本并通过标准输出获取输出的 AJAX 函数。

视图.py

from django.shortcuts import render

def index(request):
    return render(request,'homepage/page.html')

主页/page.html

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <title>test</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

        <script type="text/javascript">
            $(function()
            {
                $('#clickme').click(function(){
                    alert('Im going to start processing');
                    $.ajax({
                        url: "static/homepage/js/external_func.py",
                        type: "POST",
                        datatype:"json",
                        data: {'key':'value','key2':'value2'},
                        success: function(response){
                            console.log(response.keys);
                            console.log(response.message);                            
                        }
                    });
                });
            });
        </script>

    </head>
    <body>
        <button id="clickme"> click me </button>
    </body>
</html>

所以你可以看到我的 url 链接到external_func.py单击按钮后运行的链接。然后脚本返回一个 json。

外部函数.py

import sys
import json
import cgi

fs = cgi.FieldStorage()

sys.stdout.write("Content-Type: application/json")

sys.stdout.write("\n")
sys.stdout.write("\n")


result = {}
result['success'] = True
result['message'] = "The command Completed Successfully"
result['keys'] = ",".join(fs.keys())

d = {}
for k in fs.keys():
    d[k] = fs.getvalue(k)

result['data'] = d

sys.stdout.write(json.dumps(result, indent=1))
sys.stdout.write("\n")

sys.stdout.close()

但是,当我运行服务器并单击按钮时,控制台显示两个值的未定义,含义response.keysresponse.message未定义。

安慰

现在,当我改为将代码切换到console.log(response)in 时homepage/page.html。控制台以文本形式打印出整个external_func.py代码。

我在网上找不到解决方案。似乎人们很少在 AJAX 请求中调用 Python 脚本,我看到很多关于 AJAX 调用 php 代码的论坛帖子。

EDIT1: 我必须澄清一件事。这只是我项目的一小部分,我想对其进行一些测试。在我的实际项目中,我将在 python 中有一个需要很长时间来计算的函数,因此我更喜欢在函数处理时部分呈现带有等待图标的网页。然后该函数的输出将显示在网页上。

标签: javascriptpythonjqueryajaxdjango

解决方案


你有一个 django 应用程序,但你正在使用 CGI 来实现这个功能?为什么?为什么不简单地使函数成为另一个 django 视图?用 django 提供响应比 CGI 好得多,除非该功能显着膨胀或减慢 django。就这么简单:

from django.http import JsonResponse
def func(request):
    result = ...
    return JsonResponse(result)

如果您真的想将其分离到 CGI 脚本中,您未能获得响应的最可能原因是您的 Web 服务器未配置为处理 CGI 请求。(您的开发者工具网络选项卡对于准确诊断您得到什么样的响应非常有帮助。)出于安全原因,默认情况下不启用 CGI。您需要告诉 Apache(或您正在使用的任何 Web 服务器)应该为该目录启用 CGI,并且它应该与.py文件相关联。


推荐阅读