Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.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 Django-提交无效表单后单击“提交”按钮重定向_Ajax_Django_Forms_Submit - Fatal编程技术网

Ajax Django-提交无效表单后单击“提交”按钮重定向

Ajax Django-提交无效表单后单击“提交”按钮重定向,ajax,django,forms,submit,Ajax,Django,Forms,Submit,我有一个django项目,其中我有一个由ajax加载的div中的表单 当我提交带有空字段的表单时,它返回带有所需字段的表单 当我再次点击submit时,它会重定向到表单的操作,而不是像第一次提交时那样在div中重新加载表单并显示错误 有人知道错误可能发生在哪里吗?我想象在我的django项目的ajax或视图中的某个地方 以下是第二次提交返回的内容: {"success": false, "form": "<head>\n\n</head>\n<body>\n&

我有一个django项目,其中我有一个由ajax加载的div中的表单

当我提交带有空字段的表单时,它返回带有所需字段的表单

当我再次点击submit时,它会重定向到表单的操作,而不是像第一次提交时那样在div中重新加载表单并显示错误

有人知道错误可能发生在哪里吗?我想象在我的django项目的ajax或视图中的某个地方

以下是第二次提交返回的内容:

{"success": false, "form": "<head>\n\n</head>\n<body>\n<form action=\"/cookbook/createrecipe/\" method=\"POST\" name=\"recipeform\" id=\"createrecipeform\">\n\t<table>\n\t\t<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='c5ea952ee2144b377b375d91b0843c75' /></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\" id=\"id_reset_recipe\" /></td></tr>\n\t</table>\n\t<p><input type=\"submit\" value=\"Submit\"></p>\n</form>\n</body>"}
以下是create_form.html模板:

<head>

</head>
<body>
<form action="{% url cookbook.views.createrecipe %}" method="POST" name="recipeform" id="createrecipeform">
    <table>
        {% csrf_token %}
        {{ form.as_table }}
    </table>
    <p><input type="submit" value="Submit"></p>
</form>
</body>
{% extends "cookbook/base.html" %}
{% load pagination_tags %}
{% load comments %}


    <h1>{{ user }}'s Cookbook</h1>

<ul>
{% block nav-cookbooks %}
<li><a class="nav-inactive" href="/cookbooks/">Cookbooks</a></li>
{% endblock %}
{% block nav-account %}
<li><a class="nav-active" href="/account/">My Cookbook</a></li>
{% endblock %}
</ul>
{% block content %}
{% autopaginate recipe_list 6 %}
    <div id="recipe_cont">
            {% for recipe in recipe_list %}
        <div class="recipe">
            <div class="button">    
            <a href="{% url cookbook.views.userrecipe recipe.id %}" style="display: none;"></a>   
            <img src="{{ STATIC_URL }}chicknbraw.jpg" alt="" height="70" width="70" style="display:inline;" />
            <h4>{{ recipe.name }}</h4>
             </div>
            <h5>{{ recipe.author }}</h5>
            <h5>Prep Time: {{ recipe.prep_time }} minutes</h5>

            <h6><a href="/addrecipe/{{ recipe.id }}">Add Recipe</a>
                <a href="/removerecipe/{{ recipe.id }}">Remove Recipe</a></h6>
        </div>
    {% endfor %}
    </div>

    <div id="popupContact" class="popup">
            <a id="popupContactClose" style="cursor:pointer;float:right;">x</a>
            <p id="contactArea">
            <h1 style="text-align:center">Create New Recipe</h1>
            {% include 'cookbook/create_form.html' %} 
            </p>
    </div>
    <div id="backgroundPopup">
    </div>  
    <div id="col2-footer">
    {% paginate %}
    <p id="recipe_order_text"> order by: <a href="/userbook/ordered/name">abc</a>|<a href="/userbook/ordered/date">date</a> 
    </div>

{% endblock %}

{% block footer %}
        <a class="create" style="cursor:pointer" >Create New Recipe</a>
{% endblock %}

{%csrf_令牌%}
{{form.as_table}}

以下是包含创建表单模板的帐户模板:

<head>

</head>
<body>
<form action="{% url cookbook.views.createrecipe %}" method="POST" name="recipeform" id="createrecipeform">
    <table>
        {% csrf_token %}
        {{ form.as_table }}
    </table>
    <p><input type="submit" value="Submit"></p>
</form>
</body>
{% extends "cookbook/base.html" %}
{% load pagination_tags %}
{% load comments %}


    <h1>{{ user }}'s Cookbook</h1>

<ul>
{% block nav-cookbooks %}
<li><a class="nav-inactive" href="/cookbooks/">Cookbooks</a></li>
{% endblock %}
{% block nav-account %}
<li><a class="nav-active" href="/account/">My Cookbook</a></li>
{% endblock %}
</ul>
{% block content %}
{% autopaginate recipe_list 6 %}
    <div id="recipe_cont">
            {% for recipe in recipe_list %}
        <div class="recipe">
            <div class="button">    
            <a href="{% url cookbook.views.userrecipe recipe.id %}" style="display: none;"></a>   
            <img src="{{ STATIC_URL }}chicknbraw.jpg" alt="" height="70" width="70" style="display:inline;" />
            <h4>{{ recipe.name }}</h4>
             </div>
            <h5>{{ recipe.author }}</h5>
            <h5>Prep Time: {{ recipe.prep_time }} minutes</h5>

            <h6><a href="/addrecipe/{{ recipe.id }}">Add Recipe</a>
                <a href="/removerecipe/{{ recipe.id }}">Remove Recipe</a></h6>
        </div>
    {% endfor %}
    </div>

    <div id="popupContact" class="popup">
            <a id="popupContactClose" style="cursor:pointer;float:right;">x</a>
            <p id="contactArea">
            <h1 style="text-align:center">Create New Recipe</h1>
            {% include 'cookbook/create_form.html' %} 
            </p>
    </div>
    <div id="backgroundPopup">
    </div>  
    <div id="col2-footer">
    {% paginate %}
    <p id="recipe_order_text"> order by: <a href="/userbook/ordered/name">abc</a>|<a href="/userbook/ordered/date">date</a> 
    </div>

{% endblock %}

{% block footer %}
        <a class="create" style="cursor:pointer" >Create New Recipe</a>
{% endblock %}
{%extensed“cookbook/base.html”%}
{%load pagination_tags%}
{%loadcomments%}
{{user}}的食谱
    {%block nav cookbooks%}
  • {%endblock%} {%block nav account%}
  • {%endblock%}
{%block content%} {%automagine recipe_list 6%} {配方列表%中配方的百分比} {{recipe.name} {{recipe.author} 准备时间:{{recipe.Prep_Time}分钟 {%endfor%} | {%endblock%} {%block footer%} 创建新配方 {%endblock%}
很抱歉放了这么多代码,但这一切似乎都依赖于另一段代码,所以我认为所有相关的代码都会有帮助

谢谢你能给我的任何帮助


katie

在您的javascript中,您劫持表单以便它通过ajax提交,但随后您在表单上调用replaceWith,因此被劫持的表单将被删除并替换为新的、未被劫持的表单。要解决这个问题,你可以

1) 只替换表单的内容-这应该有效,因为您只将事件附加到表单本身,而不是它的子元素

2) 将js编写为一个函数,您可以首先在初始表单上调用它,然后在通过ajax加载的任何新表单上调用它

更新:例如

<script type="text/javascript"> 
$(document).ready(function(){

    function hijack() {
        var form = $('form#createrecipeform');
        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');
                    } else {        
                        console.log('failure');
                        var newForm = data.form;
                        form.replaceWith(newForm);
                        hijack();
                    }
                })
            });
            return false;
        });
    };

    hijack();

});
</script> 

$(文档).ready(函数(){
函数劫持(){
var form=$('form#createrecipeform');
表格提交(功能(e){
e、 预防默认值();
log('ajax表单提交函数调用成功');
//表格=$(本);
console.log(表单)
var serialized_form=form.serialize();
$.ajax({type:“POST”,
url:$(this.attr('action'),
数据:序列化的表单,
成功:(功能(数据){
log('ajax成功调用函数成功');
data=$.parseJSON(数据);
if(data.success){
console.log('success');
}否则{
console.log('failure');
var newForm=data.form;
表格。替换为(新表格);
劫持();
}
})
});
返回false;
});
};
劫持();
});

我应该编写哪个js作为函数?你是说我在帖子顶部写的整个js函数?是的,只是表单。提交(…)调用。将其放入函数中,然后直接调用它,并在replaceWith()部分之后调用它。但是我的replaceWith()函数包含在我的表单中。submit()。我怎么称呼它?对不起,如果我今天有点笨-我刚做完期末考试