首页 > 解决方案 > 将 var 从 JavaScript 返回到 Python

问题描述

我有一个这样的 HTML 容器:

<div class="col-6">
  <div class="card ">
    <div class="card-header py-2">Container Left</div>
    <div id="leftContainer" class="list-group" style="height:225px; overflow-y: scroll">
        {% for item in item_history %}
           <a href="#" data-set="5000" id = "{{forloop.counter}}" class="list-group-item py-0 list-group-item-action">{{ item }}</a>
        {% endfor %}                      
    </div>
  </div>
</div>

<p id = "output"></p>    <!-- For DEBUG output -->

我有一个这样的 JS,其中一半是我的。我能够将 var 中的值打印item_selected回 所在的 HTML 页面<p id="output>"

<script>
    $("#leftContainer > a").click(function(event){
        event.preventDefault();
        $("#leftContainer > a").removeClass("active");
        $(this).addClass("active");

        var leftDataSet = parseInt($(this).attr("data-set"));        
        var item_selected = $(this).text();
        document.getElementById("output").innerHTML = item_selected

        // Found this while googling, supposed to send data back to Python.
        var xmlhttp;
        if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        // xmlhttp.onreadystatechange=function(){ // really not sure what this block does?!
        //     if (xmlhttp.readyState==4 && xmlhttp.status==200){
        //         document.getElementById("output").innerHTML=xmlhttp.responseText;
        //     }
        // }
        xmlhttp.open("GET",item_selected,true);  // just send item_selected
        xmlhttp.send();
    });
</script>

我想在选择时从列表框/容器中发送选择,该选择当前存储在 JavaScript 中的变量item_selected. 我想将此信息发送回呈现此页面/模板的 Python。

你能帮我吗; 我知道 Python 3,不擅长 JS/JQuery。我使用的框架是 Django。我使用如下方法从后端渲染此页面render

# myapp/views.py
def render_view_results(self, request, projectid):
    return render(request, 'myapp/index.html',{'item_history':items})

另外,我不想使用此处建议的 GET 方法将信息从 HTML/JS 发送回 Python

标签: javascriptpythonjquerypython-webbrowser

解决方案


推荐阅读