2401_83940696 2024-07-24 11:57 采纳率: 2.1%
浏览 2
已结题

为什么点击按钮后没有反应?

以下是我的代码,我利用ajax实现数据的传递给后端,额咯为什么现在点击登录按钮后页面不跳转
前端代码

<html>
<head>
    <meta http-equiv="content-type" content="text/html;
    charset=UTF-8">
    <meta name="viewport" content="width=device-width,
    initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>登录</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css'%}">
    <link rel="stylesheet" href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.css'%}">
    <link rel="stylesheet"
          href="{% static 'plugins/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.min.css'%}">
</head>
<body>
<div class="account">
    <h2 style="margin-top:0">用户登录</h2>
     <form id="smsForm" method="POST" style="margin-top:20px;" novalidate>
        {% csrf_token %}
        {% for field in form %}
        {% if field.name == 'code' %}
        <div class="form-group" style="margin-top:20px;">
            <label> {{ field.label}}</label>
            <div class="clearfix">
                <div class="col-md-6" style="padding:0;">{{field}}
                <span class="error-msg" style="color:red;position:absolute"></span></div>
                <div class="col-md-6"><input id="btnSms" type="button" class="btn btn-default" value="点击获取验证码"></div>
            </div>
            <span class="error-msg" style="color:red;position:absolute"></span>
        </div>
        {% else %}
        <div class="form-group" style="margin-top:20px;">
            <label> {{ field.label}}</label>
            {{field}}
            <span class="error-msg" style="color:red;position:absolute"></span>
            {% endif %}
            {%endfor%}

        <input id="btnSubmit" style="height:35px;width:200px; margin-left:90px; font-size:17px;" type="button" value="登录"
                       class="btn btn-info">

            <div>
                 <span style="float: right; margin-top:20px;">已有账号.<a style=" text-decoration:none;" href=" ">去登录</a ></span>
            </div>
        </div>
    </form>
</div>
<script src="{% static 'js/jquery-3.5.1/jquery-3.5.1.min.js'%
 //页面加载完自动执行函数
    $(function(){
        bindClickBtnSms();
        bindClickSubmit();
        });

     //点击提交登录
        function bindClickSubmit() {
            $('#btnSubmit').click(function(){
                $(".error-msg").empty();
                //收集数据
                //发送到后台
                $.ajax({
                    url:"/login1/",
                    type:"POST",
                    data:$('#smsForm').serialize(),
                    dataType:"JSON",
                    success:function(res){
                        if(res.success){
                            location.href=res.data;
                       }else{
                        //错误信息
                            $.each(res.error,function(key,value){
                                $('#id_'+key).next().text(value[0]);
                            })
                        }
                    }
                })
            })
        }


    //点击获取验证码的按钮绑定事件
        function bindClickBtnSms(){
            $('#btnSms').click(function(){

            //获取用户输入的手机号
            var mobile=$('#id_mobile').val();

            $.ajax({
                url:"/send/sms/",
                type:"GET",
                data:{mobile: mobile,tpl: "login"},
                dataType: 'json',
                success:function(res){
                    //ajax请求发送成功后,自动执行函数
                    if (res.status){
                        sendSmsRemind();
                    }else{
                        //错误信息
                        $.each(res.error,function(key,value){
                            $('#id_'+key).next().text(value[0]);
                            })
                        }
                    },
                     error:function(xhr,status,error){
                        console.log('ajax请求失败:'+error)}
                })
            })
        }
        //倒计时
        function sendSmsRemind() {
            var $smsBtn=$('#btnSms');
            $smsBtn.prop('disabled',true);  //禁用
            var time =60;
            var remind=setInterval(function (){
                $smsBtn.val(time + '秒重新发送');
                time=time-1;
                if (time<1){
                    clearInterval(remind);
                    $smsBtn.val('点击获取验证码').prop('disabled',false);
                }
            },1000)
        }
</script>
</body>
</html>

后端代码

def login1(request):
    if request.method == 'GET':
        form = loginForm()
        return render(request, 'login1.html', {'form': form})

    form = loginForm(data=request.POST)
    if form.is_valid():
        # 用户输入正确,登录成功
        mobile = form.cleaned_data.get('mobile')
        # 把用户名写入到session中
        user_object = models.Username.objects.filter(mobile=mobile).first()

        request.session['user_id'] = user_object.id
        request.session['user_name'] = user_object.username
        return JsonResponse({'status': True, 'data': '/menu/'})
    return JsonResponse({'status': False, 'error': form.errors})
class loginForm(BootStrapForm):
    mobile = forms.CharField(label="手机号",
                             validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])
    code = forms.CharField(label="短信验证码")

    def clean_mobile(self):
        mobile = self.cleaned_data['mobile']
        exists = models.Username.objects.filter(mobile=mobile).exists()
        if not exists:
            raise ValidationError('手机号不存在')
        return mobile

    def clean_code(self):
        code = self.cleaned_data.get('code')

        mobile = self.cleaned_data.get('mobile')
        if not mobile:
            return code

        conn = get_redis_connection()
        redis_code = conn.get(mobile)
        if not redis_code:
            raise ValidationError('验证码已失效')
        redis_str_code = redis_code.decode('utf-8')
        if code.strip() != redis_str_code:
            raise ValidationError('验证码错误,请重新输入')
        return code

  • 写回答

2条回答 默认 最新

  • 阿里嘎多学长 2024-07-24 12:19
    关注

    以下内容由AIGC及阿里嘎多学长共同生成、有用望采纳:


    根据您提供的代码和问题描述,以下是一些建议和可能的解决方案:

    1. 检查AJAX请求的URL

    确保前端发起的AJAX请求URL与后端定义的路由URL完全匹配。如果URL不一致,AJAX请求将无法正确到达后端。

    2. 修正AJAX的dataType

    在您的AJAX请求中,dataType被设置为大写的"JSON",这可能会导致问题。通常,我们使用小写的"json"

    $.ajax({
        url: "/login1/",
        type: "POST",
        dataType: "json", // 改为小写
        data: $('#smsForm').serialize(),
        success: function(res) {
            // ...
        }
    });
    

    3. 检查后端响应

    确保后端返回的JSON响应格式正确,并且包含success字段。如果successtrue,则data字段应该包含跳转的URL。

    4. 检查前端JavaScript错误

    打开浏览器的开发者工具,查看控制台是否有JavaScript错误。错误可能会阻止AJAX请求的执行。

    5. 确保按钮绑定了正确的事件

    登录按钮的类型是button,这意味着它不会自动提交表单。您已经使用JavaScript绑定了点击事件,这是正确的。但是,请确保事件处理函数bindClickSubmit在页面加载时被正确调用。

    6. 检查后端表单验证逻辑

    确保后端的表单验证逻辑能够正确处理表单数据,并且没有逻辑错误。

    7. 网络问题

    如果网络连接存在问题,AJAX请求可能无法成功发送或接收响应。检查网络连接是否正常。

    8. 后端路由和视图函数

    确保后端的路由和视图函数login1能够正确处理POST请求,并且返回正确的JSON响应。

    示例代码修正

    以下是对您的代码的一些建议性修正:

    • 修正AJAX的dataType
    • 确保后端返回的JSON响应格式正确。
    function bindClickSubmit() {
        $('#btnSubmit').click(function(){
            $(".error-msg").empty();
            $.ajax({
                url: "/login1/",
                type: "POST",
                dataType: "json", // 确保使用小写
                data: $('#smsForm').serialize(),
                success: function(res){
                    if(res.success){
                        // 确保res.data是正确的URL
                        location.href = res.data;
                    }else{
                        $.each(res.error, function(key, value){
                            $('#id_'+key).next().text(value[0]);
                        });
                    }
                },
                error: function(xhr, status, error) {
                    // 可以在这里添加错误处理逻辑
                    console.error("AJAX请求失败:", error);
                }
            });
        });
    }
    

    如果您在应用这些更改后仍然遇到问题,请提供更多的信息,例如浏览器控制台中的错误信息或后端日志,以便进一步分析和解决问题。

    评论 编辑记录

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 7月25日
  • 创建了问题 7月24日

悬赏问题

  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图
  • ¥15 UE5.1局部变量对蓝图不可见
  • ¥15 一共有五道问题关于整数幂的运算还有房间号码 还有网络密码的解答?(语言-python)
  • ¥20 sentry如何捕获上传Android ndk 崩溃
  • ¥15 在做logistic回归模型限制性立方条图时候,不能出完整图的困难
  • ¥15 G0系列单片机HAL库中景园gc9307液晶驱动芯片无法使用硬件SPI+DMA驱动,如何解决?