需要代码方法/建议[python,Django,html]

2024-06-26 13:48:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用django和python,我的目标是能够进行某种类型的python函数调用(无需刷新页面)以基于onclick事件显示不同的信息。你知道吗

下面的一些通用代码显示了我的设置。本质上,当parent2中的一个按钮被单击时,我希望能够使用该按钮id对某个python函数进行函数调用。然后我想基本上重新呈现页面的一部分,以便在parent1中显示结果。你知道吗

我不知道这是多么现实,但如果有任何帮助,在正确的方向将不胜感激。你知道吗

<div id="parent1">
    <div class="child_style">
        {%for i in mydata1%}
            <div> my child 0</div>
            ...
        {% endfor %}
    </div>
</div>
<div id = "parent2">
    <div class="other_style">
        {%for j in mydata2%}
            <div><div><div><div><a id="..">Button0</a></div></div></div></div>
            ...
        {% endfor %}
    </div>
</div>

Tags: djangoindividchild目标forstyle
1条回答
网友
1楼 · 发布于 2024-06-26 13:48:41

将此函数添加到视图.py你知道吗

from django.http import HttpResponse

@api_view(["GET" , "POST"])

def demo(request):

  buttonId=request.GET.get('button-id',None)
  return HttpResponse(json.dumps({"result":"you have clicked the button"+buttonId}))

这里,buttonId将是所提到的按钮id。。。你知道吗

然后,把这个加到你的网址.py你知道吗

from django.urls import re_path
#import views.py file as view

urlpatterns = [
re_path(r'^demo$', view.demo,name='demo'),
]

现在,您可以在javascript代码中使用AJAX调用这个函数,从而得到可以在<div id="parent1">中更新的响应,如下所示

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
$.ajax({
        url: '/demo',
        data: JSON.stringify({'button-id':'demo-button'}),
        dataType: 'json',
        contentType: "application/json",
        success: function (data) {
            console.log(data['result'])
        }
    });
</script>

这里,您正在请求中传递一个JSON对象{'button-id':'demo-button'},其中demo-button是您的按钮id。 得到一个JSON {"result":"you have clicked the demo-button"}响应,您可以通过调用data['result']来获取值。你知道吗

您可以用自己的函数替换console.log(data['result']

请注意:您应该更改<a>标记。。。相反,您可以将<button>onClick事件侦听器一起使用。。 就像

<div><div><div><div><button id="some_id" onClick="myFunc(this.id);">Button</button></div></div></div></div>

其中myFunc()是。。。你知道吗

function myFunc(id){
  $.ajax({
    url: '/demo',
    data: JSON.stringify({'button-id':id}),
    dataType: 'json',
    contentType: "application/json",
    success: function (data) {
      console.log(data['result'])
    }
  });
}

相关问题 更多 >