【发布时间】:2019-03-16 03:45:11
【问题描述】:
我正在尝试传递变量,我正在从视图中获取模板,但它显示在网络浏览器(chrome)的预览中,但未显示在实际屏幕上。 以下是我的视图文件:
analyzer=SentimentIntensityAnalyzer()
data={}
with open('today_5th_oct_new.csv','r',newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
data[row[0]]=float(row[1])
analyzer.lexicon.update(data)
def index(request):
return render(request, "gui/index.html")
@csrf_exempt
def output(request):
sentences = request.POST.get('name',None)
senti = analyzer.polarity_scores(sentences)
context_dict = {'sentiment': senti}
return render(request,"gui/index.html", context = context_dict)
以下是我的模板-
<!doctype html>
<html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head>
<body>
<form action>
Enter Sentence:<input id = "name" type = "text" name = "EnterSentence" encoding = "utf-8"><br>
<input onclick = "testfunction()" type = "button" value = "Submit" >
</form>
<div><strong>Score is {{ sentiment }}</strong></div>
</body>
<script>
var testfunction = () => {
var test = document.getElementById("name").value
console.log(test)
$.ajax({
type: "POST",
dataType: "json",
url: 'output/',
data:{
csrfmiddlewaretoken: '{{ csrf_token }}',
'name': test
},
success: function(response) {
console.log("Succesful return firm ajax call");
},
error: function(result){
console.log("Failure");
}
});
}
</script>
我在预览中观察到所需的输出,而不是在实际页面上。 如何解决?
【问题讨论】:
-
context 应该返回索引函数本身,然后只在 ajax 调用的模板中可用,你应该返回 HttpResponse 作为 JSON 然后你可以从 ajax 成功函数访问它
-
能否详细说明方法
标签: django html django-templates django-views