简体   繁体   English

如何从单个 HTML 按钮同时执行 JavaScript 和 Django?

[英]How to execute JavaScript and Django concurrently from a single HTML button?

My end-goal is to process my Django view when a button is clicked (to save database info), as well as executing some JavaScript (to display a bootstrap success alert).我的最终目标是在单击按钮时处理我的 Django 视图(以保存数据库信息),以及执行一些 JavaScript(以显示引导成功警报)。 However, the bug or potential limitation I'm encountering is that I can only do one or the other.但是,我遇到的错误或潜在限制是我只能做一个或另一个。 I confirmed this to true by simply removing the onclick="somefunction()" parameter from the button element.我通过简单地从按钮元素中删除onclick="somefunction()"参数来确认这一点。 If it's removed, the response is "posted" successfully to my Django view.如果它被删除,响应将成功“发布”到我的 Django 视图。 If it's kept, only the JavaScript function is executed.如果保留,则仅执行 JavaScript function。

Here is my code:这是我的代码:

HTML: HTML:

{% csrf_token %}
<form method="POST" class="form_group">
  <!-- ...some unrelated bootstrap stuff -->
  <div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal" id="cancel-button-id">Cancel</button>
    <button type="submit" class="btn btn-primary" onclick="indicate_if_successful()" id="save-customer-button-id" name="save_customer" value="save_customer">Save customer info</button>
    <!-- The button above is the one having issues -->
  </div>
</form>

Django view Django 视图

def add(response):  # This function doesn't get executed if 'onclick' exists

    if response.method == "POST":  
        if response.POST.get("save_customer"):
            pass  # The code I want to execute

So in order to execute both the JavaScript function and Django view, what are my options?因此,为了同时执行 JavaScript function 和 Django 视图,我有哪些选择? Should I be doing all of this differently in the first place?我应该首先以不同的方式做这一切吗? I'm open to any alternative.我对任何选择持开放态度。

onclick="somefunction()" added some lock on your btn. onclick="somefunction()"在您的 btn 上添加了一些锁定。 You can use document.getElementById('save-customer-button-id').addEventListener('click', function(e){...}) , then in function body write code to alert and default behavior(send a form).您可以使用document.getElementById('save-customer-button-id').addEventListener('click', function(e){...}) ,然后在 function 正文中编写代码以提醒和默认行为(发送表单)。

But, i think, it will so fast, that user may not see it.但是,我认为,它会如此之快,以至于用户可能看不到它。

your javascript indicate_if_successful() function should return true after it is executed therefore it will run first and after it's completion the form will be submitted also it's better to use onsubmit event for form tag here您的 javascript indicator_if_successful indicate_if_successful() function 在执行后应该返回true因此它将首先运行,完成后表单将被提交,最好在此处使用onsubmit事件作为表单标签

<form method="POST" class="form_group" onsubmit="indicate_if_successful()">

</form>

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

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