简体   繁体   English

如何将 django 上下文值传递给 javascript 变量?

[英]How to pass django context values to the javascript variable?

I want to pass all the values of the {{ i.nsn }} turn by turn to the ajax script.我想将{{ i.nsn }}的所有值依次传递给 ajax 脚本。

{% for i in dibbs %}

<p>{{ i.nsn }}</p>

{% endfor %}

If I tried the ajax script in the way如果我顺便尝试了 ajax 脚本

{% for i in dibbs %}
  <script>
      var nsn = {{ i.nsn }}
      console.log("Hello")
         $('.togglebtn').on("click",function(){
         console.log("Hello")
         $.ajax({
            type: 'GET',
            url: "http://localhost:8000/toggle/"+nsn,
            contentType: 'application/json',
            success: function (data) {
                  appendData(data);
                   function appendData(data) {
            var mainContainer = document.getElementById("switch_{{forloop.counter}}");
            for (var i = 0; i < data.length; i++) {
                var div = document.createElement("div");
                div.innerHTML = '<tr>' + data[i].line_items + ' ' + data[i].nomenclature+'</tr>' ;
                mainContainer.appendChild(div);
            }
        }
            }
  });
  });




      </script>

{% endfor %}

The ajax script also repeats as per the loop. ajax 脚本也根据循环重复。

My url is different for every nsn.我的 url 对于每个 nsn 都是不同的。 I want to send a single ajax request when I clicked in the button.当我点击按钮时,我想发送一个 ajax 请求。

I want to execute a single ajax function for a single click removing the for loop.我想执行单个 ajax function 单击删除 for 循环。

I think you can try to fetch value from p tag and pass it to your ajax我认为您可以尝试从 p 标签中获取值并将其传递给您的 ajax

{% for i in dibbs %}
  <p>{{ i.nsn }}</p>


  <script>
    var nsn = ctrl.getElementsByTagName('p')[0].innerHTML;
      console.log("Hello")
         $('.togglebtn').on("click",function(){
         console.log("Hello")
         $.ajax({
            type: 'GET',
            url: "http://localhost:8000/toggle/"+nsn,
            contentType: 'application/json',
            success: function (data) {
                  appendData(data);
                   function appendData(data) {
            var mainContainer = document.getElementById("switch_{{forloop.counter}}");
            for (var i = 0; i < data.length; i++) {
                var div = document.createElement("div");
                div.innerHTML = '<tr>' + data[i].line_items + ' ' + data[i].nomenclature+'</tr>' ;
                mainContainer.appendChild(div);
            }
        }
            }
  });
  });




      </script>

{% endfor %}

You can also hide the p tag if you don't want to display如果不想显示也可以隐藏 p 标签

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM