后台返回Json数据
views.py中 前端请求
data为向后端传递的参数,利用JS得到输入的值。
ajax_get请求
<script>
$.ajax({
url: 'http://127.0.0.1:9500/cbv/server-json/',
type: 'GET',
dataType: 'json',
success: function(res){
// 请求成功后返回的数据在 res 中
this.servers = res
console.log("yan", this.servers)
}
});*/
### 箭头函数简洁
axios.get("http://127.0.0.1:9500/cbv/server-json/",).then(res => {
this.servers = res.data
});
},
});
</script>
js点击事件,ajax 发送post请求
JS代码
<script>
$(".Pushkey").on("click", function () {
let id = $(this).parent().siblings().first().text();
$.ajax({
url: "{% url 'octopus:connection' %}",
type: "POST",
data: {
"server_id": id,
'csrfmiddlewaretoken': '{{ csrf_token }}', # post请求认证
},
dataType:"json",
success: function (res) {
if (res.status) {
alert("操作成功!") # 显示操作是哦否成功
} else {
alert("操作失败!")
}
}
})
})
</script>
后端通过过滤id,分别取出服务器连接表字段,利用字符串拼接,执行免密,返回一个变量,前端展示是否执行成功
class ConnectionView(ListView):
queryset = Server.objects.filter(connection__user__isnull=False)
# model=Server
context_object_name = "server"
template_name = "octopus/connection.html"
def post(self, request):
rerver_id = request.POST.get("server_id")
server = Server.objects.filter(id=rerver_id).first()
ip = server.manager_id
user = server.connection.user
pwd = server.connection.password
port = server.connection.port
shell_comm = "ssh-copy-id -p {port} {user}@{ip}".format(
port=port, user=user, ip=ip
)
print(shell_comm)
file_dir = "/opt/CMDB_kulong/cmdbteam/adminIE/ssh_all.sh"
stat, reslut = subprocess.getstatusoutput(f"sh {file_dir} {shell_comm} {1}")
if not stat:
return JsonResponse({"status": True})
else:
return JsonResponse({"status": False})
网友评论