如何在按钮单击时调用Django函数?

如何在按钮单击时调用Django函数?,第1张

如何在按钮单击时调用Django函数?

这是一种纯Javascript的简约方法。我使用JQuery,但您可以使用任何库(甚至根本没有库)。

<html>    <head>        <title>An example</title>        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>        <script> function call_counter(url, pk) {     window.open(url);     $.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {         alert("counter updated!");     }); }        </script>    </head>    <body>        <button onclick="call_counter('http://www.google.com', 12345);"> I update object 12345        </button>        <button onclick="call_counter('http://www.yahoo.com', 999);"> I update object 999        </button>    </body></html>

替代方法

您可以通过以下方式更改链接,而不是放置Javascript代码:

<a target="_blank"          href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlenpre:''}}">    Check It Out</a>

并在您的

views.py

def YOUR_VIEW_DEF(request, pk):    YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)    return HttpResponseRedirect(request.GET.get('next')))


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5642725.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存