如何在一次单击中执行JS函数和Django后端方法调用? [英] How to execute JS functions and Django backend method call in same click?

查看:39
本文介绍了如何在一次单击中执行JS函数和Django后端方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当单击按钮或链接时,我有两种方法要执行一种是将信息发送给第三者的Javascript,第二种是将更新数据库中字段的后端Django方法.这样,我可以控制JavaScript Function仅执行一次.

I have 2 methods I want to execute when button or link is clicked One is a Javascript that will send information to a 3rd party and the 2nd one is a backend Django method that will update a field in the database. This way I can control that JavaScript Function will execute only once.

理想情况下,JavaScript应该首先执行,并且只有在执行之后,后端方法才会被触发

Ideally, Javascript should execute first and only after its execution the backend method will be triggered

我尝试将其合并到同一链接中,但这是错误的,因为仅执行javascript

I tried to combine it in the same link but this is wrong since only javascript executes

<a href="{% url 'add_to_production_board' pk=soproduct.id uri=request.build_absolute_uri %}" onclick="AddCardToTrello()">Add to Trello</a>

我在这里有什么选择?我可以从JavaScript调用后端方法吗?

What are my options here ? Can I call my backend method from JavaScript?

更新:

尽管有所有很好的答案,但就我而言,棘手的事情是如何生成后备呼叫的 {%url'add_to_production_board'pk = soproduct.id uri = request.build_absolute_uri%}

Despite all the great answers the tricky thing in my case how the backed call is generated {% url 'add_to_production_board' pk=soproduct.id uri=request.build_absolute_uri %}

我使用Django作为后端,从JavaScript调用后端方法与直接单击之间可能存在一些差异.发生的是,当从JS域名中调用该名称时,该名称被切断了.

I use Django as my backend and probably there some difference between invoking the backend method from within JavaScript vs direct click. What happens is that when it is called from within JS domain name gets cut off.

window.location.href =/production/production/order/board/5/127.0.0.1:8000/production/soproduct/details/5/

window.location.href = /production/production/order/board/5/127.0.0.1:8000/production/soproduct/details/5/

实际链接为

http://127.0.0.1:8000/production/production/order/board/5/http://127.0.0.1:8000/production/soproduct/details/5//

因此,以某种方式,当我从Javascript调用该方法时,它将切断URL(域名)的第一部分,这可能会破坏JS脚本.因此,所有答案均无济于事.我不确定Ajax,因为到目前为止还无法正常工作.

So somehow when I call the method from Javascript it cuts off my first part of URL(domain name) and this breaks the JS script probably. So none of the answers works. I am not sure about the Ajax since was not able to make it to work so far.

推荐答案

要扩展@TrampolineTales答案,由于您的两个操作之一是导航到另一个页面,因此您可以

To expand @TrampolineTales answer, since one of your two actions is a navigation to a different page, you can

function addCardThenGo(url) {
    AddCardToTrello();
    window.location.href = url;
}

然后

<a onclick="addCardThenGo({% url 'add_to_production_board' pk=soproduct.id uri=request.build_absolute_uri %})">Add to Trello</a>

这篇关于如何在一次单击中执行JS函数和Django后端方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆