【问题标题】:Adding multiple parameters to a JS script from HTML从 HTML 向 JS 脚本添加多个参数
【发布时间】:2021-11-11 12:38:36
【问题描述】:

我想将一些数据从我的 Python 视图函数传递到使用 HTML 的 JS 脚本。这是我的视图函数

def home(request):
    if request.method == 'POST':
        params = GameOfLifeForm(request.POST)
        if params.is_valid():
            starting_grid = get_starting_grid(params.cleaned_data)
            to_html = {
                'animation': True,
                'gameoflifeform': params,
                'start_grid': starting_grid,
            }
        else:
            to_html = {
                'animation': False,
                'warning_msg': 'Something went wrong. Try once again.'
            }
        return render(request, 'get_animations/home.html', to_html)
    else:
        form = GameOfLifeForm()
        return render(request, 'get_animations/home.html', {'gameoflifeform': form})

我的表单包含四个参数,其中一个名为iterations,这是我想传递给 JS 脚本的那个。此外,我想通过start_grid

我尝试在我的 HTML 文件中按以下方式进行操作

{{ start_grid | json_script:"start-grid" }}
<script
  type="text/javascript"
  src="{% static 'js/runGameOfLife.js' %}"
></script>

然后在我的JS脚本中我写了

var startGrid = JSON.parse(document.getElementById("start-grid").textContent);
console.log(startGrid);

完美运行,我在控制台中打印出网格。类似的,我可以从 HTML 中获取 iterations

{{ gameoflifeform.iterations.value | json_script:"iterations"}}
<script
  type="text/javascript"
  src="{% static 'js/runGameOfLife.js' %}"
></script>

当我尝试将这两个变量添加到我的 JS 脚本中时,它不起作用。

{{ gameoflifeform.iterations.value | json_script:"iterations"}}
{{ start_grid | json_script:"start-grid" }}
<script
  type="text/javascript"
  src="{% static 'js/runGameOfLife.js' %}"
></script>

如何将多个变量传递到我的 JS 脚本中?最好的方法是什么?

【问题讨论】:

    标签: javascript html python-3.x django


    【解决方案1】:

    最好结合使用 ajax 和视图函数,如果你学会了这个模式,你可以完成很多事情:

    views.py

    def my_view_function(request):
    
        ''' this method accepts data from the front end, 
            processes it, and returns a response '''
    
        # unpack post request:
        first_value = request.POST.get('first_key')
    
        # do some logic:
        ...
    
        # pack response
        response = {
            "second_key" : "second_value"
        }
    
        # return a json response:
        return JsonResponse(response)
    

    scripts.js

    function post_request() {
    
      /* set an event to trigger this method
         this method will then send data to the backend
         and process the response */
    
      // send an ajax post request:
      $.ajax({
        type : 'POST',
        url : 'the_url',
        data : {
          first_key : 'first_value'
        },
        success : function(response) {
     
          // unpack response
          second_value = response.second_key
    
          // do some logic
          ...
        }
      });
    
    }
    

    一旦了解了这一点,您就可以在前端和后端之间无缝地来回传递数据。如果您需要更多详细信息,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-27
      • 2013-06-20
      • 1970-01-01
      • 2012-11-07
      • 2017-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多