search
HomeWeb Front-endJS TutorialImplement registration function based on Ajax and forms components (including code)

This article shares with you the registration function based on Ajax and forms components through example code. Friends who need it can refer to

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="/static/imghwm/default1.png"  data-src="{{ getstatic }}img/TIM截图20180205110238.png"  class="lazy"   alt="Implement registration function based on Ajax and forms components (including code)" >
    </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 class="img-thumbnail lazy"  src="/static/imghwm/default1.png"  data-src="{{ getstatic }}img/registersideimg.png"  id="avatar_img"   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="/static/imghwm/default1.png"  data-src="{{ getstatic }}img/registersideimg.png"  class="lazy"   alt="Implement registration function based on Ajax and forms components (including code)" >
      </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>

The code above is just HTML, and the 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=&#39;csrfmiddlewaretoken&#39;]").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>

##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

##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))

Userifor’s img in Model

avatar = models.FileField(upload_to=&#39;avatar/&#39;, default="/avatar/default.gif", verbose_name="主键")

Note: upload_to: By default, the folder is created in the root directory. If it is created to a specified location, it needs to be set in the setting. Configure media.

For example: you want the files uploaded by users 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})

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中的使用

The above is what I organized For everyone, I hope it will be helpful to everyone in the future.

Related articles:

Detailed explanation of the steps to use Ajax


##Summary of three methods for Ajax to achieve cross-domain access


jQuery uses

ajax

Detailed explanation of the steps to obtain data across domains

The above is the detailed content of Implement registration function based on Ajax and forms components (including code). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

See all articles

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools