在Django问题中使用ajax的javascript-POST请求

时间:2016-09-07 07:20:21

标签: javascript jquery python ajax django

我是一名初学者和自学成才的程序员,并且自己编写了代码。我试图使用ajax使用Javascript post请求并面临一些持续的问题。代码中有很多错误,希望你们通过解释来纠正它。这是我的base.js文件:

var user = {
signup : function() {
    var firstname = document.signupform.first_name.value;
    var lastname = document.signupform.last_name.value; 
    var username = document.signupform.username.value;
    var email = document.signupform.email.value;
    var password = document.signupform.password.value;
    var confirmpassword = document.signupform.confirmpassword.value;
    if (firstname == "")
    {
        alert("Please provide your first name!")
        document.signupform.first_name.focus();
    }
    else if (username == "")
    {
        alert("Please provide the username!")
        document.signupform.username.focus();
    }
    else if (email == "")
    {
        alert("Please provide your Email!")
        document.signupform.email.focus() ;
    }

    else if (password == "")
    {
        alert("Please enter a valid password")
        document.signupform.password.focus() ;
    }
    else if (password != confirmpassword) 
    {
        alert("Passwords do not match.");
        document.signupform.confirmpassword.focus() ;
    }
    else
    {
        data = {"firstname":firstname, "lastname":lastname, "username":username, "email":email,"password":password};
        this.postRequest(data);
    }
    return false
},

postRequest:function(data,url,form) 
{
    $.ajax({
              type: "POST",
              url: '',
              data: data,
              success: function(data){
                if(data["success"])
                    {

                    window.location.href = '{% url home %}'

                    }
                else
                    {
                        alert(data["error"])
                    }
                }
            });
},

views.py:

class UserFormView (TemplateView):
template_name = "signup.html"
#display signup blank form
def get(self, request,*args,**kwargs):
    context = super(UserFormView,self).get_context_data(**kwargs)
    return self.render_to_response(context)


#process form data
def post(self, request,*args,**kwargs):
    context = {}
    data = request.POST
    user = get_user_model().objects.create(username=data["username"],first_name=data["firstname"],email=data["email"],last_name=data["lastname"])
    user.set_password(data["password"])
    user.save()
    user.backend = "django.contrib.auth.backends.ModelBackend"
    if user is not None:
        login(request, user)
        context["success"] = True
        # return redirect("home")
    else:
        context["success"] = False
        context["error"] = "The username is already taken!"  

        return self.render_to_response(context)

我正在点击'我的signup.html中的函数:

<a class="btn btn-success" href="javascript:void(0)" onclick="user.signup()">Sign Up</a>

我也遇到了csrf的错误。

1 个答案:

答案 0 :(得分:1)

如果直接将数据传递给服务器,则需要传递csrf令牌,否则只需将{%csrf_token%}放入表单中,并在验证后提交表单数据。

var formData = new FormData($(this)[0]);  ## Active   
$.ajax({
        url: "{% url 'apply_job' %}",
        type: 'POST',
        data: formData,
        async: true,
        cache: false,
        contentType: false,
        processData: false,

        success: function (returndata)
          {
              if(returndata.status == 'success')
                {document.getElementById('result').innerHTML = returndata.result
                  Callback();
                }
              else if(returndata.status == 'error')
                {
                    document.getElementById('result').innerHTML = returndata.result

                    Callback();
                }

          }

      });