将var从JavaScript返回到Python

时间:2018-11-28 05:23:05

标签: javascript python jquery python-webbrowser

我有一个这样的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中的值打印回到<p id="output>"所在的HTML页面。

<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})

此外,我不想使用建议的here

将信息从HTML / JS发送回Python

0 个答案:

没有答案