Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/88.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
Javascript DjangoAjax验证_Javascript_Jquery_Python_Ajax_Django - Fatal编程技术网

Javascript DjangoAjax验证

Javascript DjangoAjax验证,javascript,jquery,python,ajax,django,Javascript,Jquery,Python,Ajax,Django,我一直在想如何在django中使用ajax,但我找不到解决方案 以下是my view.py: 从django.shortcuts导入render、render_to_响应、RequestContext、HttpResponseRedirect 从.forms导入注册表单 从django.contrib导入消息 #在这里创建您的视图。 def home(请求): 表单=注册表单(request.POST或None) 如果form.is_有效(): save\u it=form.save(comm

我一直在想如何在django中使用ajax,但我找不到解决方案

以下是my view.py:

从django.shortcuts导入render、render_to_响应、RequestContext、HttpResponseRedirect
从.forms导入注册表单
从django.contrib导入消息
#在这里创建您的视图。
def home(请求):
表单=注册表单(request.POST或None)
如果form.is_有效():
save\u it=form.save(commit=False)
保存它
#messages.success(请求“感谢加入!”)
#返回HttpResponseRedirect(“/thank-you/”)
返回render\u to\u响应(“home.html”,
本地人(),

context\u instance=RequestContext(request))
您需要使用jQuery或Object发送Ajax请求。(我在提供的代码中没有看到您这样做)

要使用jQuery,您需要执行以下操作:

<script>
$.ajax({
    type: "POST",
    url: "url_to_your_view",
    data: $('#id_of_your_form').serialize()
}).done(function(msg) {
    log_thank_you_msg();  // log thank you message using JavaScript or jQuery
});    
</script>
<html>
# your contents here
<body>
<div id="ajax-form-div">
<form method='POST' id="ajax-form-date" action='your url here'> {% csrf_token %}
    {{ form.as_p }}
    <button id="submit-btn" class='btn btn-success'>Submit</button>
</form>
</div>
</body>
</html>

以下是带有CSRF令牌的jQuery AJAX帖子:

$(function () {


    $('.btn btn-success').on('click', function (e) {
            // add csrf token to your post
            var csrf = document.cookie.match(/csrftoken=([\w]+)/);
            var data = $('.styled-form').serialize();
            var request = $.ajax({
                    url: window.location.pathname,
                    type: 'post',
                    'csrfmiddlewaretoken' : csrf? csrf[1] : null,
                    'data': data
            });
            // callback handler that will be called on success
            request.done(function (response, textStatus, jqXHR){
                console.log('Success')
                // log a message to the console
            });

            // callback handler that will be called on failure
            request.fail(function (jqXHR, textStatus, errorThrown){
                // log the error to the console
                console.error(
                    "The following error occured: "+
                    textStatus, errorThrown
                );
            });
        }
    });
鉴于:

if form.is_valid():
    if request.is_ajax():
        save_it = form.save(commit=False)
        save_it.save()
        # messages.success(request, 'Thank you for joining!')
        # return HttpResponseRedirect('/thank-you/')

使用以下步骤获得所需的结果:

视图.py“

那么你的home.html应该是这样的:

<script>
$.ajax({
    type: "POST",
    url: "url_to_your_view",
    data: $('#id_of_your_form').serialize()
}).done(function(msg) {
    log_thank_you_msg();  // log thank you message using JavaScript or jQuery
});    
</script>
<html>
# your contents here
<body>
<div id="ajax-form-div">
<form method='POST' id="ajax-form-date" action='your url here'> {% csrf_token %}
    {{ form.as_p }}
    <button id="submit-btn" class='btn btn-success'>Submit</button>
</form>
</div>
</body>
</html>

#你的内容在这里
{%csrf_令牌%}
{{form.as_p}}
提交
然后创建一个新的模板名“form.html”:

{%csrf\u令牌%}
{{form.as_p}}
然后创建一个类似“Thanke.html”的感谢页面:


谢谢!谢谢

最后编写ajax:

<script>
$.ajax({
    type: "POST",
    url: "URL OF SAME METHOD OR .",
    data: $('#ajax-form-date').serialize()
}).success(function(responce) {
    $("#ajax-form-div").html(responce)
});    
</script>

$.ajax({
类型:“POST”,
url:“相同方法的url或。”,
数据:$('#ajax表单日期')。序列化()
}).成功(功能(响应){
$(“#ajax表单div”).html(响应)
});    
如果表格有效,您将获得感谢mas,如果表格无效,您将再次获得带有错误消息的新表格

请注意,jquery应该加载到您的页面上。ajax将得到调用


希望这会对您有所帮助。

你好,Yogesh,非常感谢您的帮助,一切正常,但它会将页面刷新为带有感谢信息的空白页面。我希望它保持在同一区域,而不刷新。我做错了什么吗?如果request.method==“POST”和request.is_ajax():我必须取出request.is_ajax才能让它工作。我找到了!我需要在.ajax结尾添加一个返回false
<div>
<p> Thank you!!!!!!!!!!!!!!!!!!! </p>
</div>
<script>
$.ajax({
    type: "POST",
    url: "URL OF SAME METHOD OR .",
    data: $('#ajax-form-date').serialize()
}).success(function(responce) {
    $("#ajax-form-div").html(responce)
});    
</script>