Ajax生成Token
HTML代码:
<tbody> {% for host_obj in hosts_obj %} <tr class="no-records-found"> <td>{{ forloop.counter }}</td> <td>{{ host_obj.hostname }}</td> <td>{{ host_obj.manage_ip }}</td> <td>{{ host_obj.manage_port }}</td> <td>{{ host_obj.idc_room }}</td> <td> <select class="selectpicker" tabindex="-98" id="role_{{ host_obj.id }}"> {% for role in request.user.business_role.all %} <option value="{{ role.id }}">{{ role }}</option> {% endfor %} </select> </td> <td> <button name="generate" class="btn btn-danger btn-rounded generate" onclick="Generator(this, {{ host_obj.id }})">Generate</button> <input name="token_value" type="text" disabled value=""> </td> <td> <button class="btn btn-success btn-rounded"><a href="https://172.16.65.129:4200/" target="_blank">Connect</a></button> </td> </tr> {% endfor %} </tbody>
JS代码:
<script> // 生成Token功能,获取host_id、role_id通过Ajax传递到后台生成Token并展示到前端 function Generator(self, host_id) { role_ele = "#role_" + host_id + " option:selected"; role_id = $(role_ele).val(); $.ajaxSetup({ data: {csrfmiddlewaretoken: '{{ csrf_token }}'} }); $.ajax({ type: "POST", data:{host_id: host_id, role_id: role_id}, url:"{% url "generator_token" %}", dataType:"JSON", success:function (result) { console.log(result); $(self).next().val(result.token); } }); } </script>