【问题标题】:reset form when div is closed using ajax使用ajax关闭div时重置表单
【发布时间】:2012-05-11 11:26:09
【问题描述】:

当我关闭一个 div 时如何将我的表单重置为原始状态

我正在使用 ajax 和 django

一个建议是在我的表单中使用 reset_recipe 字段,如果设置为 true 将重置配方

这是我的 disablePopup 函数:

function disablePopup($contact_selector){
//disables popup only if it is enabled
if(popupStatus==1){
    $("#backgroundPopup").fadeOut("fast");
    $contact_selector.fadeOut("fast");
    popupStatus = 0;
    var form = $("form#createrecipeform");
    console.log(form);
    form.submit(function(e) {
    e.preventDefault();
    console.log('ajax form submission function called successfully.');
    form = $(this);
    console.log(form);
    var serialized_form = form.serialize();
        $.ajax({ type: "POST", 
            url: $(this).attr('action'),
            data: serialized_form, 
            success: (function(data) { 
                console.log('ajax success function called successfully.');
                data = $.parseJSON(data);
                if (data.success) {
                    console.log('success');
                    var newForm = data.form;
                    form.replaceWith(newForm);
                } else {
                    console.log('failure');
                    var newForm = data.form;
                    form.replaceWith(newForm);  
                }
            })
        });
        return false;
    });

}

}

这是我创建食谱的视图

def createrecipe(request):
        print "entering createrecipeview"
        if request.method == 'POST':
            print "form is a post"
            form = RecipeForm(request.POST)
            if form.is_valid():
                print "form is valid"
                form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
                form = form.save()
                if form.cleaned_data['reset_recipe'] == "True"://here is the line that uses the reset_recipe function but right ow it is not working 
                    print "reset recipe"
                    form = RecipeForm(initial = {"original_cookbook": request.user.cookbooks.all()[0]})
                    t = loader.get_template('cookbook/create_form.html')
                    c = RequestContext(request, {
                    'form': form,
                    })

                    data = {
                    'replace': True,
                    'form': t.render(c),
                    'success': False,
                    }

                    json = simplejson.dumps(data)
                    return HttpResponse(json,mimetype='text/plain')
                t = loader.get_template('cookbook/create_form.html')
                c = RequestContext(request, {
                'form': form,
                })

                data = {
                'replace': True,
                'form': t.render(c),
                'success': True,
                }

                json = simplejson.dumps(data)
                return HttpResponse(json, mimetype='text/plain')
            else:
                print "form is invalid"
                form = RecipeForm(request.POST)
                t = loader.get_template('cookbook/create_form.html')
                c = RequestContext(request, {
                    'form':form,
                })

                data ={
                    'form': t.render(c),
                    'success': False,
                }

                json = simplejson.dumps(data)
                return HttpResponse(json, mimetype='text/plain')

现在,当我尝试关闭 div 时,它会重定向到一个页面并给我以下代码:

{"success": false, "form": "<form action=\"/cookbook/createrecipe/\" method=\"POST\" id=\"createrecipeform\">\n\t<table>\n\t\t<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='3fb6b9952f50edbe7654666ef20a6900' /></div>\n\t\t<tr><th><label for=\"id_name\">Name:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input id=\"id_name\" type=\"text\" name=\"name\" maxlength=\"200\" /></td></tr>\n<tr><th><label for=\"id_author\">Author:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input id=\"id_author\" type=\"text\" name=\"author\" maxlength=\"100\" /></td></tr>\n<tr><th><label for=\"id_picture\">Picture:</label></th><td><input type=\"file\" name=\"picture\" id=\"id_picture\" /></td></tr>\n<tr><th><label for=\"id_ingredients\">Ingredients:</label></th><td><ul class=\"errorlist\"><li>This field cannot be null.</li></ul><textarea id=\"id_ingredients\" rows=\"10\" cols=\"40\" name=\"ingredients\"></textarea></td></tr>\n<tr><th><label for=\"id_steps\">Steps:</label></th><td><ul class=\"errorlist\"><li>This field cannot be null.</li></ul><textarea id=\"id_steps\" rows=\"10\" cols=\"40\" name=\"steps\"></textarea></td></tr>\n<tr><th><label for=\"id_prep_time\">Prep time:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input type=\"text\" name=\"prep_time\" id=\"id_prep_time\" /></td></tr>\n<tr><th><label for=\"id_type\">Type:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><select name=\"type\" id=\"id_type\">\n<option value=\"\" selected=\"selected\">---------</option>\n<option value=\"SW\">Sandwich</option>\n<option value=\"AP\">Appetizers</option>\n<option value=\"SD\">Sauces and Dressings</option>\n<option value=\"SS\">Soups and Salads</option>\n<option value=\"VG\">Vegetables</option>\n<option value=\"RG\">Rice, Grains and Beans</option>\n<option value=\"PA\">Pasta</option>\n<option value=\"BR\">Breakfast</option>\n<option value=\"MT\">Meat</option>\n<option value=\"SF\">Seafood</option>\n<option value=\"BP\">Bread and Pizza</option>\n<option value=\"DT\">Desserts</option>\n</select><input type=\"hidden\" name=\"reset_recipe\" value=\"False\" id=\"id_reset_recipe\" /></td></tr>\n\t</table>\n\t<p><input type=\"submit\" value=\"Submit\"></p>\n</form>"}

另外需要注意的是页面重定向到表单操作页面

抱歉,代码这么多,但这一切似乎都是相关的

谢谢

凯蒂

【问题讨论】:

    标签: ajax django forms reset


    【解决方案1】:
    $("#createrecipeform").attr('reset_recipe', "True");
    

    只会给表单元素添加一个属性:

    <form reset_recipe="True" id="createrecipeform">
    

    您需要在名为 reset_recipe 的表单中添加一个输入元素。

    在表单中添加隐藏字段:

    reset_recipe = forms.CharField(widget=django.forms.widgets.HiddenInput, required=False)
    

    并将其值设置为 True(而不是向表单添加属性):

    $("#id_reset_recipe").val("True");
    

    看起来您只是在提交表单(没有 AJAX):

    $("#createrecipeform").submit();
    

    您需要通过 XHR 提交:

    $("#createrecipeform").submit(function(event){
        /* stop form from submitting normally */
        event.preventDefault(); 
    
        /* get form field values */
        var serialized_data = $( this ).serialize();
    
        /* Send the data using post and put the results in the form */
        $.post( url, serialized_data,
          function( data ) {
              $("#createrecipeform").replace( data.form );
          }
        );
     });
    

    还要为 json 使用正确的 mime 类型:

    return HttpResponse(json, mimetype='application/json')
    

    但如果你只是想重置表单,通常可以使用:

    $("#createrecipeform").reset()
    

    【讨论】:

    • 当你没有为 json 使用正确的 mimetype 时会发生什么 - 当我切换我的 mime 类型时它似乎不再工作我的食谱表单的 id 是 createrecipeform 而不是 recipe_reset 所以我不明白 $("#id_reset_recipe").val("True"); 你发给我的代码谢谢 sunn0
    • 我意识到的另一件事是我也想重置错误 - 而不仅仅是表单中的内容。现在,当在表单中发现错误时,它会在它说是必需的字段上方列出每个错误。我怎样才能摆脱那些呢?
    • 我已经更新了我的 disablepopup 你能告诉我为什么我提交 ajax 的方法是错误的吗?使用 ajax 有很多相互冲突的方法,我想确定正确的使用方法,谢谢 sunn0
    • 你能发一个链接到你的网站吗?
    • 它是一个 django 项目,所以我正在本地开发它,不幸的是有什么办法可以将它发布到某个地方并且它可以正常工作
    猜你喜欢
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2015-06-25
    相关资源
    最近更新 更多