Python之路64-Ajax

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python之路64-Ajax相关的知识,希望对你有一定的参考价值。

目录

一、Ajax提交表单

二、Ajax提交表单升级版

三、一些使用的注意事项


一、Ajax提交表单

Ajax提交表单,获取标签数据后将数据提交给后台,后台做出判断,完后返回值,Ajax接收到返回值执行回调函数,根据返回值的不同做不同的操作

默认form提交会刷新页面,而Ajax提交不会刷新页面,而是根据后台返回信息来做进一步操作


urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^business$‘, views.business),
    url(r‘^host$‘, views.host),
    url(r‘^test_ajax$‘, views.test_ajax),
]


views.py

def test_ajax(request):
    h = request.POST.get("hostname")
    i = request.POST.get("ip")
    p = request.POST.get("port")
    b = request.POST.get("b_id")
    if h and len(h) > 5:
        models.Host.objects.create(hostname=h,
                                   ip=i,
                                   port=p,
                                   # b=models.Business.objects.get(id=b),
                                   b_id=b)
        return HttpResponse("OK")
    else:
        return HttpResponse("太短了")


host.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hide{
            display: none;
        }
        .shade{
            position: fixed;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            background-color: black;
            opacity: 0.6;
            z-index: 5;
        }
        .add-model{
            position: fixed;
            height: 300px;
            width: 400px;
            top: 50%;
            left: 50%;
            margin-top: -150px;
            margin-left: -200px;
            background-color: white;
            border: 1px solid red;
            z-index: 10;
        }
    </style>
</head>
<body>
    <h1>主机列表(对象)</h1>
    <div>
        <input id="add_host" type="button" value="添加"/>
    </div>
    <table border="1">
        <thead>
            <tr>
                <th>序号</th>
                <th>主机名</th>
                <th>IP</th>
                <th>端口</th>
                <th>业务线名称</th>
            </tr>
        </thead>
        <tbody>
            {% for row in v1 %}
                <tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
                    <td>{{ forloop.counter }}</td>
                    <td>{{ row.hostname }}</td>
                    <td>{{ row.ip }}</td>
                    <td>{{ row.port }}</td>
                    <td>{{ row.b.caption }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

    <h1>主机列表(字典)</h1>
    <table border="1">
        <thead>
            <tr>
                <th>主机名</th>
                <th>业务线名称</th>
            </tr>
        </thead>
        <tbody>
            {% for row in v2 %}
                <tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
                    <td>{{ row.hostname }}</td>
                    <td>{{ row.b__caption }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

    <h1>主机列表(元祖)</h1>
    <table border="1">
        <thead>
            <tr>
                <th>主机名</th>
                <th>业务线名称</th>
            </tr>
        </thead>
        <tbody>
            {% for row in v3 %}
                <tr hid="{{ row.0 }}" bid="{{ row.2 }}">
                    <td>{{ row.1 }}</td>
                    <td>{{ row.3 }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    <div class="shade hide"></div>
    <div class="add-model hide">
        <form action="/host" method="POST">
            <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" style="display: inline-block;padding: 5px; background-color: blue;color: white">悄悄提交</a>
            <input id="cancel" type="button" value="取消">
        </form>
    </div>
    <script src="/static/jquery-1.12.4.js"></script>
    <script>
        $(function () {
            $("#add_host").click(function () {
                $(".shade,.add-model").removeClass("hide");

            });
        });
        $(function () {
            $("#cancel").click(function () {
                $(".shade,.add-model").addClass("hide");
            });
        });

        $(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);
                        }
                    }
                });
            });
        });
    </script>
</body>
</html>

二、Ajax提交表单升级版

 

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^business$‘, views.business),
    url(r‘^host$‘, views.host),
    url(r‘^test_ajax$‘, views.test_ajax),
]

 

views.py

def test_ajax(request):
    import json
    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")
        if h and len(h) > 5:
            models.Host.objects.create(hostname=h,
                                       ip=i,
                                       port=p,
                                       # b=models.Business.objects.get(id=b),
                                       b_id=b)
        else:
            ret["status"] = False
            ret["error"] = "太短了"
    except Exception as e:
        ret["status"] = False
        ret["error"] = "请求错误"
    return HttpResponse(json.dumps(ret))


host.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hide{
            display: none;
        }
        .shade{
            position: fixed;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            background-color: black;
            opacity: 0.6;
            z-index: 5;
        }
        .add-model{
            position: fixed;
            height: 300px;
            width: 400px;
            top: 50%;
            left: 50%;
            margin-top: -150px;
            margin-left: -200px;
            background-color: white;
            border: 1px solid red;
            z-index: 10;
        }
    </style>
</head>
<body>
    <h1>主机列表(对象)</h1>
    <div>
        <input id="add_host" type="button" value="添加"/>
    </div>
    <table border="1">
        <thead>
            <tr>
                <th>序号</th>
                <th>主机名</th>
                <th>IP</th>
                <th>端口</th>
                <th>业务线名称</th>
            </tr>
        </thead>
        <tbody>
            {% for row in v1 %}
                <tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
                    <td>{{ forloop.counter }}</td>
                    <td>{{ row.hostname }}</td>
                    <td>{{ row.ip }}</td>
                    <td>{{ row.port }}</td>
                    <td>{{ row.b.caption }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

    <h1>主机列表(字典)</h1>
    <table border="1">
        <thead>
            <tr>
                <th>主机名</th>
                <th>业务线名称</th>
            </tr>
        </thead>
        <tbody>
            {% for row in v2 %}
                <tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
                    <td>{{ row.hostname }}</td>
                    <td>{{ row.b__caption }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

    <h1>主机列表(元祖)</h1>
    <table border="1">
        <thead>
            <tr>
                <th>主机名</th>
                <th>业务线名称</th>
            </tr>
        </thead>
        <tbody>
            {% for row in v3 %}
                <tr hid="{{ row.0 }}" bid="{{ row.2 }}">
                    <td>{{ row.1 }}</td>
                    <td>{{ row.3 }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    <div class="shade hide"></div>
    <div class="add-model hide">
        <form action="/host" method="POST">
            <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" style="display: inline-block;padding: 5px; background-color: blue;color: white">悄悄提交</a>
            <input id="cancel" type="button" value="取消">
            <span id="error_msg"></span>
        </form>
    </div>
    <script src="/static/jquery-1.12.4.js"></script>
    <script>
        $(function () {
            $("#add_host").click(function () {
                $(".shade,.add-model").removeClass("hide");

            });
        });
        $(function () {
            $("#cancel").click(function () {
                $(".shade,.add-model").addClass("hide");
            });
        });

        $(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) {
                        var obj = JSON.parse(data);
                        if(obj.status){
                            location.reload();
                        }else{
                            $("#error_msg").text(obj.error);
                        }
                    }
                });
            });
        });
    </script>
</body>
</html>

三、一些使用的注意事项


1.基本使用

$.ajax({
    url: "/host",
    type: "POST",
    data: {"k1": 123, "k2": "root"},
    success: function(data){

    }
})

get封装了$.ajax(),type为get
$.get(url="xxx", data={}, success=function(data){

});

get封装了$.ajax(),type为post
$.post(url="xxx", data={}, success=function(data){

});


2.永远让服务器返回一个字典

return HttpResponse(json.dumps(字典))


3.前端接收到json数据

可以用JSON.parse(data),将字符串转换成对象

取对象中的值的时候,可以用.来取(json)


本文出自 “八英里” 博客,请务必保留此出处http://5921271.blog.51cto.com/5911271/1928895

以上是关于Python之路64-Ajax的主要内容,如果未能解决你的问题,请参考以下文章

《Python学习之路 -- Python基础之切片》

[原创]java WEB学习笔记61:Struts2学习之路--通用标签 property,uri,param,set,push,if-else,itertor,sort,date,a标签等(代码片段

python成长之路第三篇_正则表达式

python成长之路第三篇_正则表达式

机器学习之路: python 实践 word2vec 词向量技术

常用python日期日志获取内容循环的代码片段