Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用ajax关闭div时重置表单_Ajax_Django_Forms_Reset - Fatal编程技术网

使用ajax关闭div时重置表单

使用ajax关闭div时重置表单,ajax,django,forms,reset,Ajax,Django,Forms,Reset,关闭div时,如何将窗体重置为其原始状态 我正在使用ajax和django 一个建议是在我的表单中使用reset_recipe字段,如果设置为true,将重置配方 以下是我的禁用弹出功能: function disablePopup($contact_selector){ //disables popup only if it is enabled if(popupStatus==1){ $("#backgroundPopup").fadeOut("fast"); $contac

关闭div时,如何将窗体重置为其原始状态

我正在使用ajax和django

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

以下是我的禁用弹出功能:

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>"}
{“success”:false,“form:“\n\t\t\t\n\t\t名称:
  • 此字段是必需的。
      • \n作者:
        • 此字段是必需的。
        • 此字段不能为空。
        • 此字段不能为空。
        \n步长:
        • 此字段是必需的。
        \n键入:
        • 此字段为必填项。
        \n------\nSandwich\nAppetizers\nSaups and salars\nSoups and salars\nVegetables\nRice,Grains and Beans\nPasta\nBreakfast\nMet\nSafood\nRead and Pizza\nAsserts\n\n\t\n\n\t\n
另一件需要注意的事情是页面重定向到表单操作页面

很抱歉有这么多代码,但似乎都很相关

谢谢

凯蒂

将仅向表单元素添加属性:

<form reset_recipe="True" id="createrecipeform">
并将其值设置为True(而不是向窗体添加属性):

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

您需要通过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使用正确的mime类型,会发生什么情况?当我切换mime类型时,它似乎不再工作,而且我的配方表单的id是createrecipeform而不是recipe_reset,因此我不理解$(“#id_reset_recipe”).val(“True”);您发送给我的一段代码谢谢Sunn0我意识到的另一件事是,我还想重置错误,而不仅仅是表单中的内容。现在,当在表单中发现错误时,它会在它所说的必填字段上方列出每个错误。我如何也消除这些错误?我已经更新了我的disablepopup。您能告诉我为什么提交此方法吗使用ajax是错误的?使用ajax有很多相互冲突的方法,我想确定正确的使用方法谢谢Sunn0你能给你的网站发送一个链接吗?这是一个django项目,所以我正在本地开发不幸的是,有没有办法我可以把它发布到某个地方,并且它可以正常工作
$("#createrecipeform").submit();
$("#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 );
      }
    );
 });
return HttpResponse(json, mimetype='application/json')
$("#createrecipeform").reset()