【问题标题】:question about django rendering , jsonresponse关于django渲染的问题,jsonresponse
【发布时间】:2022-01-25 22:16:43
【问题描述】:

我正在处理员工视图。有了这个视图,我有 2 个容器。 1 用于员工姓名,另一个应在我按下姓名后立即显示信息。我试图弄清楚 3 天,但无法弄清楚有人可以帮我吗

将渲染的索引视图

def index(request):
employe = Employe.objects.all()

context = {
    'employe': employe,

}

return render(request, 'managements/index.html', context)
    

jsonresponse 视图在这里

def employeInfo(request):
data = json.loads(request.body)
employeId = data['id_s']
action = data['action']
print(employeId)
print(action)
if action == 'get':
    check = Employe.objects.get(id=employeId)
    checkinfo, create = Employe.objects.get_or_create(object, id=employeId)
    print('check:', check, 'checkinfo', checkinfo)



return JsonResponse('context', safe=False)

模板在这里,我为此尝试了几个 nvm 组合。

    <div class="flex-container">
     <div class="flex-child magenta" >
     <div data-method="POST"   id="label1"> Medewerker info</div>
            {% csrf_token %}

            {% if action %}
            <ul>{{name.employe_info}}</ul>
            <ul>{{surname.checkinfo}}</ul>
            <ul>{{checkinfo.id}}</ul>
            <ul>{{rank.id}}</ul>
            <ul>{{employeInfo.name}}</ul>
            <ul>{{email.id}}</ul>
            <ul>{{phone.id}}</ul>
            <ul>{{name.id}}</ul>

            {% endif %}
<tr>
      <div class="flex-child green">
          <div id="label2"> Medewerke</div>
          {% for profile in employe %}
                <button id="hehe" data-id_s={{profile.id}} data-action="get" class=" btn-sm btn-outline-secondary info-employe">
                <a>{{ profile.name}}</a></button>


           {% endfor %}
      </div>

</tr>
var updateBtns = document.getElementsByClassName('info- 雇员')
   for( var i = 0; i < updateBtns.length; i++) {
   updateBtns[i].addEventListener('click', function(){
   var id_s = this.dataset.id_s
   var action = this.dataset.action
   console.log('id_s:', id_s, 'action:', action)

  if (user === 'AnonymousUser'){
      console.log('User is not authenticated')
  }else{
     infoUser(id_s, action)
     console.log('user is authenticated')
     }
   })
  }

  function infoUser(id_s, action){
  var url = '/employe_info/'

 fetch(url, {
       method: 'POST',
       headers:{
       'Content-Type':'application/json',
       'X-CSRFToken': csrftoken,
  },
       body:JSON.stringify({'id_s': id_s, 'action': action})
  })
  .then((response)=>{
     return response.json()
  })
  .then((data)=>{
    console.log('data:', data)
    location.reload()
  })
  }

srry忘了这里的js

我已经尝试了 3 天,但没有任何进展。提前谢谢你

【问题讨论】:

    标签: python json django templates render


    【解决方案1】:

    您是否尝试实现类似 AJAX 的行为?

    如果您有一个用于发送 POST 的按钮,您可以执行以下操作(注意您需要包含 jquery,因为以下代码使用 jquery 来实现 AJAX):

    &lt;button type="submit" id="employee-info-btn" data-url="{% url 'url_to_your_view_handling_the_post' %}" value="Submit button"&gt;&lt;/button&gt;

    然后当你点击按钮时有一个onclick Javascript函数来处理:

    $(document).on('click', '#employee-info-btn', function (e) {
    
        $.ajax({
            type: 'POST',
            url: $(this).data('url'),
            data: {
                // add any other HTML data attributes in this dictionary
                csrfmiddlewaretoken: getCookie('csrftoken'),
            },
            success: function (json_response) {
                // Successful AJAX response handling routine here
                // Show or hide any elements you want here e.g.
                var x = document.getElementById("id-of-element-you-want-to-show");
                x.style.display = "block";
    
                // or use the json_response here
            },
            error: function (xhr, errmsg, err) { }
        });
    })
    

    getCookie()函数的实现可以看this part of the Django documentation

    我也不太确定您是如何发送 POST 的,但我建议您将其作为带有提交按钮的表单来发送。请参阅this part of the documentation 了解如何去做。

    【讨论】:

      猜你喜欢
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-20
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      相关资源
      最近更新 更多