【发布时间】: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