【问题标题】:What is the best way to pass django form data to javascript ajax call?将 django 表单数据传递给 javascript ajax 调用的最佳方法是什么?
【发布时间】:2021-11-24 20:13:25
【问题描述】:

我有一个包含一定数量字段并使用 ajax 调用与服务器通信的表单。我想知道传递从表单的 request.post 获得的数据并将其传递回 ajax 的 javascript 成功属性的最佳方法是什么。

这是一个例子:

def ajaxView(request):
form = MyForm(request.POST or None)
if request.is_ajax() and form.is_valid():
    #1 I used to use render_to_string and Parse it in the js
    #2 or get field by field using the request.POST.get method and return it
    #3 is to serialize the form

    return JsonResponse({})
return ""

在js文件中:

function CreateAjax(e) {
e.preventDefault();

$.ajax({
    url: "/ajaxViewUrl/",
    type: "post",
    data: $("#idForm").serialize(),
    success: function (data) {
      // if the first option retreive fields by field after parse
    },
    error: () => {

    }
});

}

现在,如果表单具有少量字段,这将不是问题,我担心的是当表单具有大量字段时,无论如何我都希望减少重复获取输入值的次数表格。

【问题讨论】:

    标签: javascript django ajax django-views


    【解决方案1】:

    需要注意的是,将表单作为 html 片段返回到模态框时。

    Views.py

    @require_http_methods(["POST"])
    def login(request):
    form = BasicLogInForm(request.POST)
        if form.is_valid():
            print "ITS VALID GO SOMEWHERE"
            pass
    
        return render(request, 'assess-beta/login-beta.html', {'loginform':form})
    

    返回截断的 html 的简单视图

    表单 html 截图

    <form class="login-form" action="/login_ajx" method="Post"> 
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="header">Authenticate</h4>
      </div>
      <div class="modal-body">
            {%if form.non_field_errors %}<div class="alert alert-danger">{{ form.non_field_errors }}</div>{%endif%}
            <div class="fieldWrapper form-group  has-feedback">
                <label class="control-label" for="id_email">Email</label>
                <input class="form-control" id="{{ form.email.id_for_label }}" type="text" name="{{ form.email.html_name }}" value="{%if form.email.value %}{{ form.email.value }}{%endif%}">
                {%if form.email.errors %}<div class="alert alert-danger">{{ form.email.errors }}</div>{%endif%}
            </div>
            <div class="fieldWrapper form-group  has-feedback">
                <label class="control-label" for="id_password">Password</label>
                <input class="form-control" id="{{ form.password.id_for_label }}" type="password" name="{{ form.password.html_name}}" value="{%if form.password.value %}{{ form.password.value }}{%endif%}">
                {%if form.password.errors %}<div class="alert alert-danger">{{ form.password.errors }}</div>{%endif%}
            </div>
      </div>
      <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
    <input type="submit" value="Sign in" class="btn btn-primary pull-right"/>
    </div>
    </form>
    

    包含模式的页面

    {% 包括 "assess-beta/login-beta.html" %}

    使用包含标签加载页面加载时的片段,以便在打开模式时可用。

    Modal.js

    $(document).on('submit', '.login-form', function(){
    $.ajax({ 
        type: $(this).attr('method'), 
        url: this.action, 
        data: $(this).serialize(),
        context: this,
        success: function(data, status) {
            $('#LoginModal').html(data);
        }
        });
        return false;
    });
    

    在这种情况下使用 .on() 可以像 .live() 一样工作,将提交事件绑定到文档而不是按钮。

    【讨论】:

    • 我猜即使你没有在模态中渲染它也可以使用
    猜你喜欢
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 2019-02-04
    相关资源
    最近更新 更多