JS之ajax实现注册页,小文件传输

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h2 class="text-center">注册</h2>
            <hr>
            <form id="myform">
                {% csrf_token %}
        <p>用户名
        <input type="text" id="username" class="form-control "
    name='username'>
        </p>
        <p>密码
        <input type="password" id="password" name="password" class="form-control"
    value="{{ error.old_password }}">
        </p>
        <p>再次输入密码
      <input
    type="password" id="re_password" name="re_password" class="form-control"
    value="{{ error.new_password }}">
        </p>
    <div class="form-group">
     <label for="id_myfile">头像
      <img src="/static/img/default.png" alt="" width="80" style="margin-left: 20px" id="id_img">
      //先给img一个默认图片路径,然后隐藏文件选择input框,label指向文件选择input框,当点击img图片的时候就触发了文件选择框
    </label>
    <input type="file" name="myfile" id="id_myfile" style="display: none">
    </div>
      <button class="btn btn-primary pull-right" id="id_submit">注册</button>
    </div>
  </div>
</div>
<script>
$(
'#id_myfile').change(function () {
  
// 先获取用户上传的文件对象
  let fileObj
= this.files[0];
  // 生成一个内置对象
  let fileReader
= new FileReader();
  // 将文件对象传递给内置对象
  fileReader.readAsDataURL(fileObj);
  // 将读取出文件对象替换到img标签
  fileReader.onload
= function(){
  // 等待文件阅读器读取完毕再渲染图片
  $(
'#id_img').attr('src',fileReader.result) } });
    
// ajax提交数据
    $(
'#id_submit').click(function () {
    
// 生成一个Formdata对象
    let formData = new FormData();
    
// 往Formdata对象中添加键值
    // $('#myform').serializeArray() 得到的数据格式是[{'username':'egon'},{'password':'123'},{},{}...]
     // $.each([obj1.obj2,obj3],function(index,obj){ 执行语句 }) <==> pyhton中的for循环,index是列表中的索引
$.each($('#myform').serializeArray(),function (index,obj) { // console.log(index,obj)
       //打印 1 obj1
        //   2 obj2
        //   .... index得到的是索引
formData.append(obj.name,obj.value) }); // 手动添加文件数据 formData.append('myfile',$('#id_myfile')[0].files[0]); $.ajax({ url:'', type:'post', data:formData, // 传输文件需要指定的两个参数 processData:false, contentType:false, //告诉django不要处理数据 success:function (data) { //模拟后台处理后返回结果data,格式;{'code':100,'msg':'...', ....} if (data.code == 100){ // 跳转到登录页面 location.href = data.url //后端传来的路由地址 } else{ $.each(data.msg,function (index,obj) { //如果注册失败通过data.code的值告诉前端执行结果,然后通过data.msg告诉前端需要进行的操作 }) } } }) }); </script> </body> </html>

 

posted @ 2019-06-21 00:03  希希大队长  阅读(575)  评论(0编辑  收藏  举报