我是Django的新手,我正在试图弄清楚如何在不重新加载页面的情况下动态添加来自python脚本的内容。
目前,我的views.py文件中有两个函数。一个处理上传文件(home),另一个处理调用python脚本并处理文件(句柄)。我这样分离它的原因是因为我想按顺序填充HTML表格,因为python脚本与上传的文件一起使用。
但是,我的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'),
]
答案 0 :(得分: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")
}
});
});