zoukankan      html  css  js  c++  java
  • Ajax(一)

    Ajax

      Ajax即“Asynchronous Javascript And XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术,AJAX = 异步 JavaScriptXML标准通用标记语言的子集),AJAX 是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。传统的网页(不使用 AJAX)如果需要更新内容,必须重载整个网页页面
    1、初识
    $.ajax({
        url: '/host',               // 数据提交地址
        type: "POST",               // 提交类型
        data: {'k1': 123, 'k2': "root"},        // 提交的内容 字典格式
        success: function(data){    // 客户端会一直等待服务端返回的数值
                // data是服务器端返回的字符串
            var obj = JSON.parse(data);
        }
    })
    
    建议:永远让服务器端返回一个字典
    return HttpResponse(json.dumps(字典))
    

    2、简单的前后端交互 

     <div class="shade hide"></div>
            <div class="add-modal hide">
                <form method="POST" action="/home/">
                <div class="group">
                    <input id='host' type="text" placeholder="主机名" name="hostname" />
                </div>
    
                <div class="group">
                    <input id='ip' type="text" placeholder="IP" name="ip" />
                </div>
    
                <div class="group">
                    <input id='port' type="text" placeholder="端口" name="port" />
                </div>
    
                <div class="group">
                    <select id='sel' name="b_id">
                        {% for op in b_list %}
                        <option value="{{ op.id }}">{{ op.caption }}</option>
                        {% endfor %}
                    </select>
                </div>
                <input type="submit" value="提交" />
                <a id="ajax_submit">要上天提交</a>
                <input id="cancel" type="button" value="取消" />
    
            </form>
    
        </div>
    index.html

    Ajax代码:

    $(function(){
        $('#ajax_submit').click(function () {
            $.ajax({
                url:"/test_ajax/",
                type:"POST",
                data:{'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()},
                success:function (data) {
                    if(data=='OK'){
                        location.reload()   // 重新加载页面
                    }else {
                        alert(data);
                    }
                }
            })
        })
    })
    

    Django代码:

    def test_ajax(request):
        print(request.method)
        h = request.POST.get('hostname')
        i = request.POST.get('ip')
        p = request.POST.get('port')
        b = request.POST.get('b_id')
        print(h,i,p,b)
        if h and len(h) > 5:        # 主机名长度判断
            models.Host.objects.create(hostname=h,ip=i,port=p,b_id=b) # 创建数据
            return HttpResponse("OK")    # 返回OK 严格大小写
        else:
            return HttpResponse("主机名太短")  # 返回错误提示
    

      

    3、对前后端交互完善(当后端有问题时,前端收不到data,页面无反应) 

    <div class="add-modal hide">
                <form method="POST" action="/home/">
                <div class="group">
                    <input id='host' type="text" placeholder="主机名" name="hostname" />
                </div>
    
                <div class="group">
                    <input id='ip' type="text" placeholder="IP" name="ip" />
                </div>
    
                <div class="group">
                    <input id='port' type="text" placeholder="端口" name="port" />
                </div>
    
                <div class="group">
                    <select id='sel' name="b_id">
                        {% for op in b_list %}
                        <option value="{{ op.id }}">{{ op.caption }}</option>
                        {% endfor %}
                    </select>
                </div>
                <input type="submit" value="提交" />
                <a id="ajax_submit">要上天提交</a>
                <input id="cancel" type="button" value="取消" />
                <span id="error_msg"></span>
    
            </form>
    
        </div>
    index.html

    Ajax代码:

    $(function(){
        $('#ajax_submit').click(function () {
            $.ajax({
                url:"/test_ajax/",
                type:"POST",
                data:{'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()},
                success:function (data) {
                    console.log(data)    // data {"data": null, "status": false, "error": "u4e3bu673au540du592au77ed"}
                    var obj = JSON.parse(data);     // 反序列化 把字符串data换成对象obj
                                                    // 序列化 JSON.stringify() 把obj转换为字符串
                    if(obj.status){
                        location.reload()   // 重新加载页面
                    }else {
                        $('#error_msg').text(obj.error)
                    }
                }
            })
        })
    })
    

    Django代码:  

    import json
    def test_ajax(request):
        ret = {'status':True,'error':None,'data':None}  # 返回一个字典
        try:
            h = request.POST.get('hostname')
            i = request.POST.get('ip')
            p = request.POST.get('port')
            b = request.POST.get('b_id')
            print(h,i,p,b)
            if h and len(h) > 5:        # 主机名长度
                print("ok")
                models.Host.objects.create(hostname=h,ip=i,port=p,b_id=b)
            else:
                ret['status'] = False
                ret['error'] = '主机名太短'
        except Exception as e:
            ret['status'] = False
            ret['error'] = '请求错误'
        return  HttpResponse(json.dumps(ret))       # 对字典进行序列化
    

    4、serialize自动获取表单数据

    <form class="add-form" method="POST" action="/home/">
                <div class="group">
                    <input id='host' type="text" placeholder="主机名" name="hostname" />
                </div>
    
                <div class="group">
                    <input id='ip' type="text" placeholder="IP" name="ip" />
                </div>
    
                <div class="group">
                    <input id='port' type="text" placeholder="端口" name="port" />
                </div>
    
                <div class="group">
                    <select id='sel' name="b_id">
                        {% for op in b_list %}
                        <option value="{{ op.id }}">{{ op.caption }}</option>
                        {% endfor %}
                    </select>
                </div>
                <input type="submit" value="提交" />
                <a id="ajax_submit">要上天提交</a>
                <input id="cancel" type="button" value="取消" />
                <span id="error_msg"></span>
    
            </form>
    index.html

    Ajax代码:

    $.ajax({
        url:"/test_ajax/",
        type:"POST",         
        data:$('.add-form').serialize(),  // 获取表单数据提交 必须是form表单
        success:function (data) {
            })
    

    5、Ajax代码补充(traditional,dataType)

    Ajax代码:

    $(function(){
        $('#add_submit_ajax').click(function(){
            $.ajax({
                url: '/ajax_add_app',
                data: {'user': 123,'host_list': [1,2,3,4]},
                // data: $('#add_form').serialize(),
                type: "POST",
                dataType: 'JSON',       // 内部对传过来的数据直接执行JSON.parse 拿到的数据直接为对象而非字符串
                traditional: true,      // 添加此项 当字典里包含列表时候,后端可以getlist到里面的数据
                success: function(obj){
                    console.log(obj);
                },
                error: function () {     // 未知错误时执行,指前端收不到后台发送的obj时,执行
                }
            })
        });
    })
    

    Django代码:

    def ajax_add_app(request):
        ret = {'status':True, 'error':None, 'data': None}
    
        app_name = request.POST.get('app_name')
        host_list = request.POST.getlist('host_list')
        obj = models.Application.objects.create(name=app_name)
        obj.r.add(*host_list)
        return HttpResponse(json.dumps(ret))
    

    6、页面跳转和刷新 

    $.ajax({
        url: '/index/',
        data: {'k': 'v', 'list': [1,2,3,4], 'k3': JSON.stringfy({'k1': 'v'}))}, $(form对象).serilize() 
        type: 'POST',
        dataType: 'JSON':
        traditional: true,
        success:function(d){
            location.reload()              # 刷新
            location.href = "某个地址"     # 跳转
        }
    })
    

      

     

      

     
  • 相关阅读:
    ORA-12801/ORA-12853: insufficient memory for PX buffers: current 274880K, max needed 19722240K/ORA-04031解决方法
    关于oracle result_cache
    oracle insert、append、parallel、随后查询的redo与磁盘读写
    关于ashrpt中行源的CPU + Wait for CPU事件深入解读
    resmgr:cpu quantum 等待事件 top 1
    ORA-00600: internal error code, arguments: [kcblin_3], [103], [253952], [8192], [32769], [312], [640], [], [], [], [], []解决方法
    Oracle之with as和update用法
    oracle查询buffer cache中undo大小
    oracle group by placement可能导致错误结果的bug
    maven maven-war-plugin 解决java war项目间的依赖(两个war都可独立部署运行,maven 3.2.x亲测)
  • 原文地址:https://www.cnblogs.com/lianzhilei/p/6198002.html
Copyright © 2011-2022 走看看