Home Web Front-end JS Tutorial Use Ajax and forms to implement the functions required to register users

Use Ajax and forms to implement the functions required to register users

Mar 30, 2018 pm 03:15 PM
ajax register

This time I will bring you the functions required for registered users using Ajax and forms. What are the precautions for using Ajax and forms to realize the functions required for registered users? Here are practical cases, let’s take a look.

Front-end HTML

<!DOCTYPE html>
{% load static %}
{% get_static_prefix as getstatic %}
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" href="https://www.jd.com/favicon.ico">
  <link href="{{ getstatic }}plugins/bootstrap-3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <title>注册页面</title>
  <style>
    .title-top {
      padding: 0;
      font-size: 21px;
      margin-top: 40px;
    }
    .form-padding {
      padding-right: 65px;
    }
    .has-feedback .country-code {
      width: 53px;
      text-align: right;
      padding-right: 5px;
    }
    .mobile-control-wrap {
      display: flex;
    }
    .mobile-num {
      margin-left: 10px;
    }
    .form-horizontal .form-group {
      margin-right: -15px;
      margin-left: -15px;
    }
    .body-box {
      margin-top: 70px;
      height: 567px;
      width: 68%;
    }
    .cnblogs-btn-blue {
      color: white;
      padding: 6px 14px;
      letter-spacing: 1em;
      padding-left: 2em;
      background-color: RGB(70, 136, 214);
      text-align: center;
    }
    .cnblogs-btn-blue :hover {
      color: white;
    }
    .navbar {
      background-color: RGB(40, 62, 92);
    }
    .side-img-box {
      height: 300px;
      position: relative;
      padding-left: 0;
      margin-top: 168px;
    }
    .side-img-box img {
      position: relative;
      width: 100%;
      top: 50%;
      transform: translateY(-50%);
      border-radius: 8px;
    }
    .text-danger {
      float: right;
    }
    .img-thumbnail {
      width: 100px;
      height: 100px;
      margin-bottom: 20px;
      margin-top: -10px;
    }
    #avatr_img {
      margin-left: 237px;
    }
  </style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
  <p class="container">
    <!-- Brand and toggle get grouped for better mobile display -->
    <p class="navbar-header">
      <img src="{{ getstatic }}img/TIM截图20180205110238.png">
    </p>
    <!-- Collect the nav links, forms, and other content for toggling -->
    <p class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">首页</a></li>
        <li><a href="#">登录</a></li>
        <li><a href="#">注册</a></li>
        <li><a href="#">帮助</a></li>
      </ul>
    </p><!-- /.navbar-collapse -->
  </p><!-- /.container-fluid -->
</nav>
<p class="container body-box" style="height: 567px;">
  <p class="center-block body-content">
    <!--头部提示-->
    <p class="hidden-xs title-top col-sm-12">
      注册新用户
      <hr class="head-hr">
    </p>
    <p class="form-wrap">
      <form class="form-horizontal col-sm-8 form-padding" role="form" id="registerForm" method="post"
         novalidate="novalidate">
        <!--每一行-->
        <p id="avatr_img" class="form-group">
          <label for="avatar">
            <img id="avatar_img" class="img-thumbnail" src="{{ getstatic }}img/registersideimg.png" alt="用户头像">
            头像
          </label>  
          <input type="file" style="display: none;" id="avatar">
        </p>
        <p class="form-group">
          <p class="col-sm-2 control-label">
            <label class="w4-2" for="Email">邮       箱</label>
          </p>
          <p class="col-sm-10 has-feedback">
            {{ register_form.email }}
            <span class="text-danger"></span>
          </p>
        </p>
        <p class="form-group">
          <p class="col-sm-2 control-label">
            <label class="w4-4" for="DisplayName">昵称</label>
          </p>
          <p class="col-sm-10 has-feedback">
            {{ register_form.nik_name }}
            <span class="text-danger field-validation-error"><span id="DisplayName-error"></span></span>
          </p>
        </p>
        <p class="form-group">
          <p class="col-sm-2 control-label">
            <label class="w4-2" for="Password">密       码</label>
          </p>
          <p class="col-sm-10 has-feedback">
            {{ register_form.password }}
            <span class="text-danger field-validation-error"></span>
          </p>
        </p>
        <p class="form-group">
          <p class="col-sm-2 control-label">
            <label class="w4-4" for="ConfirmPassword">确认密码</label>
          </p>
          <p class="col-sm-10 has-feedback">
            {{ register_form.repeta_pwd }}
            <span class="text-danger field-validation-error"><span id="mobile-error"></span></span>
          </p>
        </p>
        <!--注册按钮-->
        <p class="form-group">
          <p class="col-sm-offset-2 col-sm-10">
            <span class="col-sm-12 ajax-error"></span>
            <input id="submitBtn" onclick="regesite()" type="button"
                class="btn ladda-button center-block cnblogs-btn-blue" value="登录">
          </p>
        </p>
        <!--协议提示-->
        <p class="col-sm-offset-2 register-sign">
          <span class="asterisk">*</span> “注册” 按钮,即表示您同意并愿意遵守 <a class="look-agreeon" target="_blank"
                                      href="//passport.cnblogs.com/agreement.html">用户协议</a>。
        </p>
        <!--hidden-->
        {% csrf_token %}
      </form>
      <p class="hidden-xs col-sm-4 side-img-box">
        <p class="side-line">
          <p></p>
        </p>
        <img src="{{ getstatic }}img/registersideimg.png">
      </p>
    </p>
  </p>
</p>
<script src="{{ getstatic }}js/jquery-3.2.1.min.js"></script>
<script src="{{ getstatic }}plugins/bootstrap-3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
Copy after login

The above code is just HTML, and JavaScript is in the example below

<script>
   $("#avatar").change(function () {
    var chooice_file = $(this)[0].files[0];
    var reader = new FileReader();// 注意这里,预览本地文件
    reader.readAsDataURL(chooice_file);
    reader.onload=function () {
      $("#avatar_img").attr("src",this.result)
    }
  })
  function regesite() {
    var formdata = new FormData(); //z注意这里 涉及文件上传
    formdata.append("email",$("#id_email").val());
    formdata.append("nik_name",$("#id_nik_name").val());
    formdata.append("password",$("#id_password").val());
    formdata.append("repeta_pwd",$("#id_repeta_pwd").val());
    formdata.append("valid_img",$("#avatar")[0].files[0]);
    formdata.append("csrfmiddlewaretoken",$("[name='csrfmiddlewaretoken']").val());
    $.ajax({
      url: "{% url "regeste" %}",
      type: "POST",
      data:formdata,
      contentType:false,
      processData:false,
      success: function (data) {
        response_data = JSON.parse(data)
        if(response_data.user){
          location.href="{% url " rel="external nofollow" login" %}"
        }else {
          // 清空上次错误信息
          $("form span").html("")
          $(".has-feedback").removeClass("has-error")
          $.each(response_data.error_msg,function (fiel, error_info) {
            // 显示错误信息
            $("#id_"+fiel).parent().addClass("has-error");
            $("#id_"+fiel).next().html(error_info[0]);//显示全局错误 // 注意这里
            if(fiel=="all"){
              $("#id_repeta_pwd").next().html(error_info[0]).css("color","red")
            }
          })
        }
      }
    })
  }
</script>
Copy after login

FileReader

FileReader is mainly used to read file contents into memory. Through a series of asynchronous interfaces, local files can be accessed in the main thread.

Using FileReader objects, web applications can asynchronously read the contents of files (or raw data buffers) stored on the user's computer. You can use File objects or Blob objects to specify the files or data to be processed.

Design RegisterForm component

from django import forms
from . import models
from django.forms import widgets
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
class RegisterForm(forms.Form):
  nik_name = forms.CharField(max_length=32,
                widget=widgets.TextInput(attrs={"class":"form-control"}),
                error_messages={"required":"用户不能为空"})
  email = forms.EmailField(widget=widgets.EmailInput(attrs={"class":"form-control"}),
               error_messages={"required":"邮箱不能为空", "invalid":"邮箱格式错误"})
  password = forms.CharField(min_length=5, widget=widgets.PasswordInput(attrs={"class":"form-control"}),
                error_messages={"required": "密码不能为空",
                        "min_length":"最小长度5位",
                        }
                )
  repeta_pwd = forms.CharField(widget=widgets.PasswordInput(attrs={"class":"form-control"}),
                 error_messages={"required": "密码不能为空"})
  def clean_nik_name(self):
    name = self.cleaned_data.get("nik_name")
    users = models.UserInfo.objects.filter(nik_name=name)
    if not users:
      return name
    else:
      raise ValidationError("用户已存在")
  def clean(self): //全局钩子
    pwd = self.cleaned_data.get("password")
    repeta_pwd = self.cleaned_data.get("repeta_pwd")
    if pwd and repeta_pwd:
      if pwd == repeta_pwd:
        return self.cleaned_data
      else:
        raise ValidationError("两次密码不一致")
    else:
      return self.cleaned_data
Copy after login

Server

def post(self,request):
    reg_response = {"user": None,"error_msg":""}
    register_form = RegisterForm(request.POST)
    if register_form.is_valid():
      email = request.POST.get("email")
      nik_name = request.POST.get("nik_name")
      password = request.POST.get("password")
      repeta_pwd = request.POST.get("repeta_pwd")
      valid = request.FILES.get("valid_img") #注意这里使用的request.FILES.get("")
      if not valid:
        valid = "avatardir/TIM图片20171209211626.gif"
      check_user = models.UserInfo.objects.create_user(username=nik_name,nik_name=nik_name, email=email,
                                password=password,
                                avatar=valid
                              ) # 注意这里保存导数据库中的是图片路径,并不是图片
      reg_response = {"user": "user", "error_msg": ""}
      return HttpResponse(json.dumps(reg_response))
    else:
      reg_response["error_msg"]=register_form.errors
      return HttpResponse(json.dumps(reg_response))
Copy after login

Userifor's img

avatar = models.FileField(upload_to='avatar/', default="/avatar/default.gif", verbose_name="主键")
Copy after login

Note:

upload_to: By default, the folder is created to In the root directory, if you create it to a specified location, you need to configure media in the setting.

For example: you want the files uploaded by the user to be stored separately and configured in the setting.

MEDIA_ROOT= os.path.jion(BASE_DIR,"blog","media")
//此时,用户上传文件时,先创建并将文件保存至“putImg”文件夹中,“putImg”,然后将“putImg”放至对应的路径中。
# media 配置
url(r"^media/(?P<path>.*)",sever,{"document_root":setting.MEDIA_ROOT})
Copy after login

After configuring the above url, the user can access all files under the media folder

Note:

 server ,是从django.views.static import server导入
     from . import settings //url中的使用
Copy after login

I believe you have mastered the method after reading the case in this article, please pay attention for more exciting things Other related articles on php Chinese website!

Recommended reading:

Native Ajax implementation MIME type (with code)

Determine whether it is an integer, decimal or What are the ways to write regular numbers for real numbers

The above is the detailed content of Use Ajax and forms to implement the functions required to register users. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to register multiple accounts on Xiaohongshu? Will I be discovered if I register multiple accounts? How to register multiple accounts on Xiaohongshu? Will I be discovered if I register multiple accounts? Mar 25, 2024 am 09:41 AM

As a platform integrating social networking and e-commerce, Xiaohongshu has attracted more and more users to join. Some users hope to register multiple accounts to better experience interacting with Xiaohongshu. So, how to register multiple accounts on Xiaohongshu? 1. How to register multiple accounts on Xiaohongshu? 1. Use different mobile phone numbers to register. Currently, Xiaohongshu mainly uses mobile phone numbers to register accounts. Users sometimes try to purchase multiple mobile phone number cards and use them to register multiple Xiaohongshu accounts. However, this approach has some limitations, because purchasing multiple mobile phone number cards is cumbersome and costly. 2. Use email to register. In addition to your mobile phone number, your email can also be used to register a Xiaohongshu account. Users can prepare multiple email addresses and then use these email addresses to register accounts. but

How to register a Manwa Comics account How to register a Manwa Comics account Feb 28, 2024 am 08:00 AM

On the Manwa Comics platform, there are rich comic resources waiting for everyone to explore. As long as you easily enter the official platform of Manwa Comics, you can enjoy all kinds of wonderful comic works. Everyone can easily find their favorite comics to read according to their own preferences. So how to register the official account of Manwa Comics? The editor of this website will bring you this detailed tutorial guide, hoping to help everyone in need. Manwa Comics-Official entrance: https://fuw11.cc/mw666 Manwa Comics app download address: https://www.siemens-home.cn/soft/74440.html Manwa Comics non-mainland area entrance: https: /

How to check what is registered with a mobile phone number 'Detailed explanation: APP query method for mobile phone number registration' How to check what is registered with a mobile phone number 'Detailed explanation: APP query method for mobile phone number registration' Feb 07, 2024 am 08:24 AM

I don’t know if you have such an experience. Your mobile phone often receives some inexplicable text messages, or registration information for some websites or other verification information. In fact, our mobile phone number may be bound to many unfamiliar websites, and we ourselves Even if you don’t know, what I will share with you today is to teach you how to unbind all unfamiliar websites with one click. Step 1: Open the number service platform. This technique is very practical. The steps are as follows: Open WeChat, click the plus icon in the search box, select Add Friend, and then enter the code number service platform to search. We can see that there is a number service platform. Of course, it belongs to a public institution and was launched by the National Institute of Information and Communications Technology. It can help everyone unbind mobile phone number information with one click. Step 2: Check whether the phone has been marked for me

How to register a Xiaohongshu account? What is required to register a Xiaohongshu account? How to register a Xiaohongshu account? What is required to register a Xiaohongshu account? Mar 22, 2024 am 10:16 AM

Xiaohongshu, a social platform integrating life, entertainment, shopping and sharing, has become an indispensable part of the daily life of many young people. So, how to register a Xiaohongshu account? 1. How to register a Xiaohongshu account? 1. Open the Xiaohongshu official website or download the Xiaohongshu APP. Click the &quot;Register&quot; button below and you can choose different registration methods. Currently, Xiaohongshu supports registration with mobile phone numbers, email addresses, and third-party accounts (such as WeChat, QQ, Weibo, etc.). 3. Fill in the relevant information. According to the selected registration method, fill in the corresponding mobile phone number, email address or third-party account information. 4. Set a password. Set a strong password to keep your account secure. 5. Complete the verification. Follow the prompts to complete mobile phone verification or email verification. 6. Perfect the individual

How to register 163 email How to register 163 email Feb 14, 2024 am 09:20 AM

Some users find that they do not have an account when they want to use 163 mailbox. So what should they do if they need to register an account at this time? Now let’s take a look at the 163 email registration method brought by the editor. 1. First, search the 163 Email official website in the browser and click [Register a new account] on the page; 2. Then select [Free Email] or [VIP Email]; 3. Finally, after selecting, fill in the information and click [Now Just register];

How to register a Xiaohongshu account? How to recover if its account is abnormal? How to register a Xiaohongshu account? How to recover if its account is abnormal? Mar 21, 2024 pm 04:57 PM

As one of the most popular lifestyle sharing platforms in the world, Xiaohongshu has attracted a large number of users. So, how to register a Xiaohongshu account? This article will introduce you to the Xiaohongshu account registration process in detail, and answer the question of how to recover Xiaohongshu account abnormalities. 1. How to register a Xiaohongshu account? 1. Download the Xiaohongshu APP: Search and download the Xiaohongshu APP in the mobile app store, and open it after the installation is complete. 2. Register an account: After opening the Xiaohongshu APP, click the &quot;Me&quot; button in the lower right corner of the homepage, and then select &quot;Register&quot;. 3. Fill in the registration information: Fill in the mobile phone number, set password, verification code and other registration information according to the prompts. 4. Complete personal information: After successful registration, follow the prompts to complete personal information, such as name, gender, birthday, etc. 5. Settings

How to register a qooapp account How to register a qooapp account Mar 19, 2024 pm 08:58 PM

qooapp is a software that can download many games, so how to register an account? Users need to click the &quot;Register&quot; button if they don't have a pass yet, and then choose a registration method. This account registration method introduction is enough to tell you how to operate it. The following is a detailed introduction, so take a look. How to register a qooapp account? Answer: Click to register, and then choose a registration method. Specific methods: 1. After entering the login interface, click below. Don’t have a pass yet? Apply now. 2. Then choose the login method you need. 3. You can use it directly after that. Official website registration: 1. Open the website https://apps.ppaooq.com/ and click on the upper right corner to register. 2. Select registration

How to check how long it has been since WeChat registration? How to check how long you have been registered on WeChat How to check how long it has been since WeChat registration? How to check how long you have been registered on WeChat Mar 13, 2024 am 08:52 AM

WeChat is a popular social software with rich functions and many users. If you want to check how long you have been registered on WeChat, although WeChat itself does not directly provide the function of checking the registration time, we can speculate through some indirect methods. However, these methods are not absolutely accurate as various factors may affect the accuracy of the results. If you have precise requirements for the registration time, it is recommended to contact WeChat customer service for consultation. How to check how long it has been since WeChat registration? The first way to see how long you have been registered on WeChat is by checking your QQ mailbox. If you use QQ to log in to WeChat, after successful registration, your QQ mailbox will receive a welcome email from WeChat. You can search for "WeChat" in your QQ mailbox to see if there is such an email, and then determine the registration time. The second way is by looking at

See all articles