【问题标题】:Use Ajax response script into a Django HttpResponse在 Django HttpResponse 中使用 Ajax 响应脚本
【发布时间】: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


【解决方案1】:

在您的 view.py return render(request,"gui/index.html", context = context_dict 代码中缺少结尾 paranthesis


这是jQuery ajax的正确顺序:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

您的successerror 字段位于data 内。


<script>
    $(document).ready(function(){
        $("button").click(function(){
            $.ajax({url: "demo_test.txt", success: function(result){
                $("#div1").html(result);
            }});
        });
    });
    </script>
    </head>
    <body>

    <div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

    <button>Get External Content</button>

    </body>

这是一个如何使用ajax jquery 的.html 方法的例子。您可以根据自己的情况进行调整。


另外,使用下面的代码循环遍历response

  $.each( data, function( key, val ) {
    HTMLString += <li id='" + key + "'>" + val + "</li>
  });

这应该在success函数内部,然后将HTMLString传递给.html方法

为了更清楚$.each 的工作原理:

var numbers = [1, 2, 3, 4, 5, 6];
$.each(numbers , function (index, value){
  console.log(index + ':' + value); 
});

【讨论】:

  • 你能发布输出吗
  • 现在,它和截图一样,我粘贴在上面,但在预览方法中没有分数后的值
  • 不要忘记您正在获取字典作为响应。你需要遍历它
  • 您是如何使用建议的 .html 方法的?即使你不循环,它也不应该是一样的。
  • 因为您的 ajax 没有成功返回。看看你的图片,它正在安慰错误消息“失败”
猜你喜欢
  • 2016-09-03
  • 2015-06-27
  • 2010-12-04
  • 2011-04-08
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-08
相关资源
最近更新 更多