HTML-Ajax提交及后端数据传回的小坑

1.使用Ajax让浏览器悄悄提交前段表中数据,而不刷新页面。

html中的代码:


<form class="rightform" id="jsStayForm">
    <div>
        <img src="{% static 'images/rightform1.png' %}"/>
        <input type="text" name="name" id="companyName" placeholder="名字" maxlength="25" />
    div>
    <div>
        <img src="{% static 'images/rightform2.png' %}"/>
        <input type="text" name="mobile" id="companyMobile" placeholder="联系电话"/>
    div>
    <div>
        <img src="{% static 'images/rightform3.png' %}"/>
        <input type="text" name="course_name" id="companyAddress" placeholder="课程名" maxlength="50" />
    div>
    <p class="error company-tips" id="jsCompanyTips">p>
    <input class="btn" type="text" id="jsStayBtn" value="立即咨询 >" />
    {% csrf_token %}
form>

Ajax代码:

$(function(){
    $('#jsStayBtn').on('click', function(){
        $.ajax({
            cache: false,
            type: "POST",
            url:"{% url 'org:add_ask' %}",
            data:$('#jsStayForm').serialize(),
            async: true,
            success: function(data) {
                console.log(data)
                if(data.status == 'success'){
                    $('#jsStayForm')[0].reset();
                    alert("提交成功")
                }else if(data.status == 'fail'){
                    $('#jsCompanyTips').html(data.msg)
                }
            },
        });
    });
})

后端View.py中代码,其中return JSON数据有一个坑,见代码。

class AddUserAskView(View):
    '''
    用户咨询
    '''
    def post(self,request):
        userask_form = UserAskForm(request.POST)
        if userask_form.is_valid():
            user_ask = userask_form.save(commit=True)
            # return HttpResponse("{'status':'success'}", content_type='application/json')  #双引号在外面会传递不过去
            return HttpResponse('{"status":"success"}', content_type='application/json')    #一定要这样写
        else:
            # return HttpResponse("{'status':'fail','success':'咨询出错'}",content_type='application/json')  #双引号在外面会传递不过去
            return HttpResponse('{"status":"fail","msg":"咨询出错"}',content_type='application/json')   #一定要这样写



你可能感兴趣的:(Django,html)