Django实现ajax提交

  1. 云栖社区>
  2. 博客>
  3. 正文

Django实现ajax提交

甜海 2019-04-08 16:08:20 浏览214
展开阅读全文

场景:前端框架用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)



网友评论

登录后评论
0/500
评论