• django之Form组件--ajax提交


    如果想要ajax提交数据到django后台,对页面进行跳转,需要在ajax 中进行跳转,在后台进行跳转不生效

    示例代码

    views部分

    from django.shortcuts import render, redirect, HttpResponse
    
    # Create your views here.
    from day60app.form_cls import AForm
    import json
    from django.forms.utils import ErrorDict
    
    
    def ajax(request):
        if request.method == "GET":
            obj = AForm()
            return render(request, "ajax.html", {"obj": obj})
        elif request.method == "POST":
            obj = AForm(request.POST)
            ret = {"status": None, "message": None}
            print("31----", obj)
    
            if obj.is_valid():
                ret["status"] = "成功"
                print("35", ret)
                return HttpResponse(json.dumps(ret))
            else:
                # err = obj.errors
                ret["message"] = obj.errors
                return HttpResponse(json.dumps(ret))

    from 部分

    from django.forms import Form
    from django.forms import widgets
    from django.forms import fields
    from django.forms.models import ModelChoiceField
    from day60app import models
    
    class AForm(Form):
            user_id = fields.IntegerField(
                widget=widgets.Select(choices=[(1, "赖英"), (2, "春云"), (3, "星星")])
        )
            age = fields.IntegerField()

    前端页面部分

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form id="fm" action="/ajax/" method="post" novalidate>
            {{ obj.as_p }}
    
            <input type="button" value="ajax提交" id="but">
    
        </form>
        <script src="/static/jquery-3.1.1.js"></script>
    
        <script>
            $(function () {
                $("#but").click(function () {
                    $.ajax({
                        url:"/ajax/",
                        type:"POST",
                        data:$("#fm").serialize(),
                        dataType:"JSON",
                        success:function(arg){
                            console.log("26----",arg);
                            if (arg["status"] == "成功"){
                                window.location.href = "http://www.jd.com"
    
                            }
    {#                        else:#}
    
                        }
    
                    })
                })
            })
    
        </script>
    </body>
    </html>
  • 相关阅读:
    Windows 编程,程序编译使用的命令行工具。
    showmemory.c 和 hello.s 源码
    jps命令
    A亚马逊WS网上系列讲座——怎么样AWS云平台上千万用户的应用建设
    Android比较字符串是空的(isEmpty)
    NSDictionary、NSMutableDictionary基本使用
    写贤治学生:关键是要管理好自己的时间
    Spark SQL Catalyst源代码分析Optimizer
    leetcode
    SQL Server 权限管理
  • 原文地址:https://www.cnblogs.com/YingLai/p/6579934.html
Copyright © 2020-2023  润新知