所以我有一个简单的 Django 脚本,我在网上找到了一个 AJAX 函数,该函数运行 Python 脚本并通过 stdout 获取输出。
views.py
from django.shortcuts import render
def index(request):
return render(request,'homepage/page.html')
homepage/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>
所以你可以看到我的网址链接到 external_func.py
,它在单击按钮后运行。然后该脚本返回一个 json。
external_func.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.keys
和 response.message
未定义。
现在,当我将代码切换到 homepage/page.html
中的 console.log(response)
时。控制台以文本形式打印出整个 external_func.py
代码。
我在网上找不到解决方案。似乎人们很少在 AJAX 请求中调用 Python 脚本,我看到很多关于 AJAX 调用 php 代码的论坛帖子。
编辑1: 我必须澄清一件事。这只是我的项目的一小部分,我想对其进行一些测试。在我的实际项目中,我将在 python 中使用一个需要很长时间来计算的函数,因此我更喜欢在函数处理时使用等待图标部分渲染网页。该函数的输出将显示在网页上。
最佳答案
您有一个 django 应用程序,但您正在使用 CGI 来实现此功能?为什么?为什么不简单地将函数设为另一个 django View 呢?使用 django 提供响应比 CGI 优越得多,除非该功能显着膨胀或减慢您的 django。就这么简单:
from django.http import JsonResponse
def func(request):
result = ...
return JsonResponse(result)
如果您确实想将其分离到 CGI 脚本中,则无法获得响应的最可能原因是您的 Web 服务器未配置为处理 CGI 请求。 (您的开发人员工具“网络”选项卡对于准确诊断您收到的响应类型有很大帮助。)出于安全原因,默认情况下不启用 CGI。您需要告诉 Apache(或您正在使用的任何 Web 服务器)应该为该目录启用 CGI,并且它应该与 .py
文件关联。
关于javascript - Django AJAX 返回未定义而不是变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53953654/