zoukankan      html  css  js  c++  java
  • 完整版,通过ajax-get获取数据,通过ajax-post 上传数据。添加checkbox

    重点

    1.ajax-get

    获取的数据如下所示

    {'status': 'success', 'message': '获取成功', 'list': [{'model': 'app01.article', 'pk': 1, 'fields': {'title': '渺小的人类111111111', 'content': '渺小的人类渺小的人类渺小的人类渺小的人类渺小的人类xxxxxxxxxxxxxxxxxxx', 'account': 5, 'pub_date': '2018-07-09T16:19:52Z', 'read_count': 0, 'tag': [3]}}]}

    function getAjax(v) {    //通过get请求取值,获取模态对话框上面所需的值
            $.ajax({
            url: "/app01/ajax/",
            type: "GET",
            data: {'id': v },
            dataType: 'json',
            success: function(data){
                $('#testdic').val(data)
                var dic_a = data['list'][0]['fields']
                for ( var i in dic_a ){
                    console.log(i,dic_a[i])
                    $('#popup').find('[tname="' + i + '"]').val(dic_a[i]);
                }
                dic_a['account'] == "1" ? $('#checkbox_id').prop('checked',true):$('#checkbox_id').prop('checked',false)
            }})
        }
        function test11(obj) {     //点击编辑触发
            var v = $(obj).parent().parent().find('[tname="id"]').text();
            $('#popup').find('input[tname="id"]').val(v);
            getAjax(v);
        }
    

      

    2.Ajax-post

        $('#ajax_submit').click(function () {  //提交上传数据
            $.ajax({
                url: "/app01/ajax/",
                type: "POST",
                data: {'id': $('#id_id').val(),'title': $('#title_id').val(),'account_id':$('#account_id').val()},
                dataType:'json',
                success:function (data) {
                    //alert(data);//成功返回
                    if(data['status'] == "success" ){
                        location.reload();
                    }else{
                        alert(data['status']+ data['message']) //一般是显示
                    }
                }
            })
        })
    

      

    二. 后台

    Ajax接口 get+post

    class Ajax(View):
        def get (self,request,**kwargs):
            ret={'status':'success','message':'获取成功'}
            """请求数据"""
            try:
                date=Article.objects.filter(id=request.GET.get("id"))
                ret['list']=json.loads(serializers.serialize('json',date))
            except Exception as e:
                ret['message']=e
            return JsonResponse(ret)
        def post(self, request,**kwargs):
            """提交表单"""
            ret = {'status': 'success', 'message': '获取成功'}
            try:
                id=request.POST.get("id")
                title=request.POST.get("title")
                account_id=request.POST.get("account_id")
                if title and len(title) > 3:
                    pass
                v=Article.objects.filter(id=id)
                v.update(title=title,account_id=account_id)
            except Exception as e:
                ret['message'] = e
            return JsonResponse(ret)
    

      

    urls.py

    url(r'^ajax/$',views.Ajax.as_view(),name="Ajax"),
    

      

    三. 完整代码

    html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <!-- Bootstrap -->
        <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
    <div>
        <h1>XXXX的傻猫</h1>
    </div>
    <div>
    
    <table class="table" border="1px">
                <thead>
                <tr>
                    <th tname="title">IP地址</th>
                    <th tname="account">端口</th>
                    <th tname="operator">操作</th>
                </tr>
                </thead>
                <tbody>
    
                {%for obj in articles%}
                <tr>
                      <!--隐藏一个标签放数据,提交表单使用-->
                    <td tname="title">{{obj.title}}<a tname="id" style="display: none">{{obj.id}}</a></td>
                    <td tname="account">{{ obj.account }}</td>
                    <td tname="operator"><a href="javacript:void(0)" onclick="test11(this)" class="edit1"><span class="glyphicon glyphicon-edit" data-toggle="modal" data-target=".bs-example-modal-lg" aria-hidden="true"></span></a></td>
                </tr>
                {%endfor%}
                </tbody>
            </table>
    </div>
    <div id="popup" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
         <form  method="POST" style="margin: 20px 20px;">
              {% csrf_token %}
      <div class="form-group" style="display: none">   <!--隐藏一个标签放数据,提交表单使用-->
        <label for="exampleInputEmail1">id</label>
        <input id="id_id" tname="id" type="text" class="form-control" placeholder="Text input">
      </div>
      <div class="form-group">
        <label for="exampleInputEmail1">在用状态</label>
        <input id="checkbox_id" tname="account" type="checkbox" >
      </div>
      <div class="form-group">
        <label for="exampleInputEmail1">文章名称</label>
        <input id="title_id" tname="title" type="text" class="form-control" placeholder="Text input">
      </div>
      <div class="form-group">
        <label for="exampleInputPassword1">作者</label>
          <select tname="account" id="account_id" class="form-control" >
              {% for op in account %}
              <option  value="{{ op.id }}">{{ op.username }}</option>
              {% endfor %}
          </select>
      </div>
      <button id="ajax_submit" type="button" class="btn btn-default">确认</button>
       <button type="button" class="btn btn-default">取消</button>
    </form>
        </div>
      </div>
    </div>
    <div id="testdic"></div>
        <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
        <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
        <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
        <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script>
    
        function getAjax(v) {    //通过get请求取值,获取模态对话框上面所需的值
            $.ajax({
            url: "/app01/ajax/",
            type: "GET",
            data: {'id': v },
            dataType: 'json',
            success: function(data){
                $('#testdic').val(data)
                console.log(data)
                console.log(data['list'])
                var dic_a = data['list'][0]['fields']
                for ( var i in dic_a ){
                    console.log(i,dic_a[i])
                    $('#popup').find('[tname="' + i + '"]').val(dic_a[i]);
                }
                dic_a['account'] == "1" ? $('#checkbox_id').prop('checked',true):$('#checkbox_id').prop('checked',false)
            }})
        }
        function test11(obj) {     //点击编辑触发
            var v = $(obj).parent().parent().find('[tname="id"]').text();
            $('#popup').find('input[tname="id"]').val(v);
            getAjax(v);
        }
    
        $('#ajax_submit').click(function () {  //提交上传数据
            $.ajax({
                url: "/app01/ajax/",
                type: "POST",
                data: {'id': $('#id_id').val(),'title': $('#title_id').val(),'account_id':$('#account_id').val()},
                dataType:'json',
                success:function (data) {
                    //alert(data);//成功返回
                    if(data['status'] == "success" ){
                        location.reload();
                    }else{
                        alert(data['status']+ data['message']) //一般是显示
                    }
                }
            })
        })
    </script>
    </body>
    </html>
    

      

    python

    urls.py

    from django.contrib import admin
    from django.urls import path
    from django.conf.urls import url
    from app01 import views
    
    urlpatterns = [
        path('index/',views.Index.as_view() ),
        url(r'^table/$',views.Table_html.as_view(),name="Table_html"),
        url(r'^ajax/$',views.Ajax.as_view(),name="Ajax"),
    ]
    

      

    views.py

    from django.shortcuts import render,redirect,HttpResponse
    from django.http import JsonResponse
    from django.views.generic import  View
    from .models import  *
    from django.views.generic import TemplateView
    from django.core  import serializers
    import json
    # Create your views here.
    from django.views.decorators.csrf import csrf_exempt,csrf_protect
    
    class Index(View):
        def get(self,request):
            name=request.GET['name']
            print(name,"ssssss")
            a2=Account.objects.get(username=name)
            #a2.props_with_()
            #print(a2['username'])
            #b1=a1.article_set.all()
            a1 = Account.objects.all()
            #print()
            #b1=Article.objects.filter(account=a1)
            #b1=Article.objects.filter(account=a1)
            print(a1)
            return render(request,'templeate/index.html',locals())
    class Table_html(TemplateView):
        template_name = "templeate/app01/tb.html"
    
        def get_context_data(self, **kwargs):
            context = super(Table_html, self).get_context_data(**kwargs)
    
            context['articles'] = Article.objects.all()
            context['account'] = Account.objects.all()
            return context
    
        def post_context_data(self, **kwargs):
            context = super(Table_html, self).post_context_data(**kwargs)
            context['articles'] = Article.objects.all()
            return context
    class Ajax(View):
        def get (self,request,**kwargs):
            ret={'status':'success','message':'获取成功'}
            """请求数据"""
            try:
                date=Article.objects.filter(id=request.GET.get("id"))   #serializers.serialize 转django模型只能是filter 不能转get
                ret['list']=json.loads(serializers.serialize('json',date))  #构造json类型!!! 一定要json.loads,里面类型为str,需要转成json
            except Exception as e:
                ret['message']=e
            return JsonResponse(ret)
        def post(self, request,**kwargs):
            """提交表单"""
            ret = {'status': 'success', 'message': '获取成功'}
            try:
                id=request.POST.get("id")
                title=request.POST.get("title")
                account_id=request.POST.get("account_id")
                if title and len(title) > 3:
                    pass
                v=Article.objects.filter(id=id)
                v.update(title=title,account_id=account_id)
            except Exception as e:
                ret['message'] = e
            return JsonResponse(ret)
    

      

  • 相关阅读:
    php常用函数总结
    PHP常用函数(收集)
    Web开发者的最爱 5个超实用的HTML5 API
    打开MySQL数据库远程访问的权限
    centos yum 安装问题
    CentOS6.4安装VNC
    删:Centos 7安装Nginx 1.8
    centos6.3安装nginx
    MySQL5.7重置root密码
    CentOS下MySQL忘记root密码解决方法【转载】
  • 原文地址:https://www.cnblogs.com/a10086/p/9411238.html
Copyright © 2011-2022 走看看