javascript - 将 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})
解决方案
推荐阅读
- angular - Angular 多个 .subscribe 用于
- assets - zipline:如何找到符号的 sid,例如“AAPL”
- c# - 使用 dot.net 客户端 SolaceSystems.Solclient.Messaging 缺少 libcrypto-1_1-x64.dll
- c# - 在同步代码中等待输入而不阻塞的最佳方法
- ruby - 红宝石:在heroku上使用credentials.yml.enc?
- mongodb - 查询 MongoDb 聚合连接两个集合
- laravel - Laravel - 在单个请求中处理大量小数据条目,总执行时间超过 2 分钟
- python - 使用 Geany IDE (Raspberry Pi Raspbian) 执行 .py 文件时出现权限被拒绝错误
- azure-eventhub - 如何禁用 eventHubs 命名空间?
- wpf - 如何解析 IContainerProvider 中某个类型的所有实例(prism 7+)