Django实现ajax提交

场景:前端框架用layui, 提交的是textarea

页面:


            <form method="POST">
                {% csrf_token %}                
                <div class="layui-form-item">
                    <div class="layui-col-md6 layui-col-xs-12">
                        <label class="layui-form-label">页面地址</label>
                        <div class="layui-input-inline">
                            <textarea class="layui-textarea" name="urlstext" placeholder="请输入地址(一行一条以http开头)"></textarea>
                            <button class="layui-btn" lay-submit="" lay-filter="srh">立即提交</button>
                            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                        </div>
                    </div>
                    <div class="layui-col-md6 layui-col-xs-12">
                        <label class="layui-form-label">查询结果</label>
                        <div class="layui-input-inline">
                            <textarea class="layui-textarea mg1em" name="res" id="resultstext">
                            </textarea>
                        </div>
                    </div>
                </div>
            </form>
javascript:


<script>
layui.use(['form', 'layer'], function () {
$ = layui.jquery;
var form = layui.form,layer = layui.layer;
var posting = false;
//监听提交
form.on('submit(srh)', function (data) {
    if (posting) return;
    posting = true;
    var loading = layer.load(1);
    var form = $(this).closest("form");
    $.ajax({
        url: "query",
        data: form.serialize(),
        dataType: 'json',
        method: 'POST',
        success: function (res) {
            var items = res.is_taken;
            if (items) {
                posting = false;
                layer.close(loading);
                $('#resultstext').val('');
                for(var itemindex in items){
                    $('#resultstext').val($('#resultstext').val()+items[itemindex]+'\n');
                }
            } else {
                posting = false;
                layer.close(loading);
                layer.msg("查询失败", { icon: 5 });
            }
        },
        error: function () {
            posting = false;
            layer.close(loading);
            layer.msg("查询失败", { icon: 5 });
        }
    });
    return false;
    });
});
</script>

服务端:


def query(request):
    urls = results = []
    res = request.POST.get("urlstext", "")
    #处理逻辑......
    data = { 'results': results }
    return JsonResponse(data)



上一篇:【Arduino】使用C#实现Arduino与电脑进行串行通讯


下一篇:阿里云服务器训练营学习(1):简单搭建个人博客