zoukankan      html  css  js  c++  java
  • Django Form表单 ajax提交

    from django.shortcuts import render, HttpResponse
    from django import forms
    from django.forms import fields, widgets
    import json
    
    
    # Create your views here.
    
    # views.py
    
    class AjaxForm(forms.Form):
        price = fields.IntegerField()
        user_id = fields.IntegerField(
            widget=(
                widgets.Select(choices=[(0, '张三'), (1, '李四'), (2, '王五'), ])
            )
        )
    
    
    def ajax(request):
        if request.method == 'GET':
            obj = AjaxForm()
            return render(request, 'ajax.html', {'obj': obj})
        else:
            obj = AjaxForm(request.POST)
            ret = {'status': None, 'message': None}
            if obj.is_valid():
                # print(obj.cleaned_data)
                # return redirect('http://www.baidu.com')  # 使用ajax提交,即使redirect,也不会跳转
                ret['status'] = 'true'
            else:
                # print(obj.errors)  # obj.errors 是一个django.forms.utils.ErrorDict对象,继承自dict(字典)数据类型,默认是ul
                # obj.errors有很多方法 默认为as_ul() 还有 as_json() as_data() as_text()
                ret['message'] = obj.errors.as_text()
    
                return HttpResponse(json.dumps(ret))      # json.dumps() 只能对python中的基本数据类型进行处理
    <!--前端-->
    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id='fm'> <span id="msg"></span>   {% csrf_token %}   {{ obj.as_p }}   <input type='button' value='提交' id='btn'> </form> <script src='/static/jquery.js'></script> <script> $(function() { $('#btn').click(function () { $.ajax({ url: 'http://127.0.0.1:8000', type: 'POST', dataType: 'JSON', data: $('#fm').serialize(), success: function (arg) { if (arg.status == 'true') { window.location.href = 'http://www.baidu.com' }else{ console.log(arg.message); $("#msg").html(arg.message); } } }) }) }) </script> </body> </html>
  • 相关阅读:
    1_Selenium环境搭建
    python functools
    python 参数注解inspect
    python 堆排序
    python functools
    python 装饰器
    python 柯里化
    python 高阶函数
    python 树
    python 函数销毁
  • 原文地址:https://www.cnblogs.com/dangrui0725/p/9671704.html
Copyright © 2011-2022 走看看