【发布时间】:2018-10-12 10:15:13
【问题描述】:
我正在尝试使用HttpResponse 将从view 获得的ajax 响应传递给template,但我不知道该怎么做?
view.py
analyzer=SentimentIntensityAnalyzer()
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
我想在页面上得分后打印senti,但我无法获得。
模板文件
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<form action = Post>
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>
</html>
【问题讨论】:
-
那么,您想显示从特定位置检索到的数据吗?
-
是的,在模板文件中的单词 score 之后
-
预期用途是什么?我假设显示的视图对应于您的 Ajax 调用的 URL - 它以 html(呈现的模板)响应。您可以轻松地将这个 html 转储到特定容器中,在您的
success回调中, -
啊,感谢您的编辑。在这种情况下,不要打扰
{{ sentiment }}模板变量。只需在此处放置一个空 div 并使用对 Ajax 调用的响应填充它。 -
你为什么又问了这个问题?正如我上次告诉你的,Ajax 在这里完全没有意义,你应该删除它。
标签: javascript ajax django