zoukankan      html  css  js  c++  java
  • ajax

    1、什么是ajax?

      1.AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。

      2.AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。

      3.AJAX 不是新的编程语言,而是一种使用现有标准的新方法。

    2、ajax与传统开发模式的区别:

      ajax开发模式:页面将用户的操作通过ajax引擎与服务器进行通信,将返回的结果给ajax引擎,然后ajax将数据插入指定位置。

      传统的开发模式:用户的每一次操作都触发一次返回服务器的HTTP请求,服务器做出处理后,返回一个html页面给用户。

    3、ajax的使用:

    1、ajax发送字符串数据

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>注册</title>
        <script type="text/javascript" src="../static/js/jquery-1.12.4.min.js"></script>
        <script type="text/javascript" src="../static/js/main.js"></script>
    </head>
    <body>
    
    <form method="post" enctype="multipart/form-data" id = "add_form">
    
        用户名:<input type="text" name="name" id="name">
        <br>
    
        邮箱:<input type="text" name="email" id = "email">
        <br>
    
        密码:<input type="text" name="pwd" id = "pwd">
        <br>
    
        确认密码:<input type="text" name="pwd1" id = "pwd1">
        <br>
    
        手机号:<input type="text" name="phone" id = "phone">
        <br>
    
        身高:<input type="text" name="height" id = "height">
        <br>
    
        图  片:<input type="file" name="picture1" id = "picture1">
        <br>
    
    
        <input type="submit" id = "regist">
    
    
    </form>
    
    <script>
        $(function () {
            $("#regist").click(function () { 
                {#用标签选择器获取需要的值#}
                var name = $("#name").val();   
                var email = $("#email").val();
                var pwd = $("#pwd").val();
                var pwd1 = $("#pwd1").val();
                var phone = $("#phone").val();
                var height = $("#height").val()
                    {#发送ajax请求#}
                    .ajax({
                        url:"/user/add",  
                        type:"post",
                        data:{"name":name,
                              "email":email,
                              "phone":phone,
                              "pwd":pwd,
                              "pwd1":pwd1,
                              "height":height},
                        {#成功后执行的函数#}
                        success:function (res) {
                            if (res.code == 200){
                                {#重定向#}
                                window.location.href="/user/login"
                            }else {
                                alert(res.message)
                            }
                        {#失败后执行的函数    #}
                        error:function f() {
                            alert("添加失败,请重新添加");
                            window.location.href="/user/add"
                            }
                        }
                    })
    
            })
    
        })
    
    
    
    </script>
    
    </body>
    ajax发送数据给后端
    def adduser():
    
        if request.method =="POST":
            name = request.form.get("name")
            pwd = request.form.get("pwd")
            pwd1 = request.form.get("pwd1")
            email = request.form.get("email")
            phone = request.form.get("phone")
            height = request.form.get("height")
            picture1 = request.files.get("picture1")
            print(picture1,name)
    
    
    
            # print(name,pwd,pwd1,email,phone,height)
    
            if not all([name,pwd,pwd1,email,phone,height]):
                flash("数据不完整,添加完整")
    
            role_phone = r'1[d]{10}$'
            role_email = r"[w]+@[w]+.[a-z]{2,3}$"
    
            result_phone = re.match(role_phone,phone)
    
            result_email = re.match(role_email,email)
    
            if not result_email:
                flash("邮箱格式不正确,请检查")
                return redirect("/user/add")
    
            if not result_phone:
                flash("手机号有误,请检查")
                return redirect("/user/add")
    
            if  pwd != pwd1:
                flash("两次密码不一致,请检查")
                return redirect("/user/add")
    
            flag = False
            try:
                # print(1111111)
                print(type(phone),type(height),type(pwd),type(email),type(pic_filename))
                user1 = User(name=name,email=email,password=pwd,phone=phone,height= int(height),pic_name = pic_filename)
                db.session.add(user1)
                db.session.commit()
                # print(22222222)
                if user1:
                    flag =True
    
            except Exception as e:
                # raise e
                db.session.rollback()
                flash("添加失败,重新添加")
                return redirect("/user/add")
    
    
            if flag:
                return redirect("/user/show")
    
        return render_template("adduser.html")
    后端处理ajax请求

    2、ajax发送文件数据

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>添加图片</title>
        <script type="text/javascript" src="../static/js/jquery-1.12.4.min.js"></script>
        <script type="text/javascript" src="../static/js/main.js"></script>
    </head>
    <body>
    
    <form enctype="multipart/form-data" id="uploadForm">
          <input type='file' name='xxx' id='pic_img'>
          <input type='button' onclick='upload()' value='点击上传'>
     </form>
    
    </body>
    
    <script>
        function upload(){
        var formData = new FormData($("#uploadForm")[0])  //创建一个forData
        formData.append('img', $('#pic_img')[0].files[0]) //把file添加进去  name命名为img
        $.ajax({
            url: "/add/picture",
            data:formData,
            type: "POST",
            async: false,
            {#当async属性的值为false时是同步的,Ajax请求将整个浏览器锁死,只有ajax请求返回结果后,才执行ajax后面的alert语句。#}
            {#当async属性的值为true时是异步的,即不会等待ajax请求返回的结果,会直接执行ajax后面的alert语句。#}
            cache: false,
            {#cache:true 如果当前请求有缓存的话,直接使用缓存。如果该属性设置为 false,则每次都会向服务器请求#}
            contentType: false,
            {#我们在 form 标签中设置了enctype = “multipart/form-data”,这样请求中的 contentType 就会默认为 multipart/form-data 。
            而我们在 ajax 中 contentType 设置为 false 是为了避免 JQuery 对其操作,从而失去分界符,而使服务器不能正常解析文件。#}
            processData: false,
            {#发送的数据将被转换为对象(从技术角度来讲并非字符串)以配合默认内容类型&quot;application/x-www-form-urlencoded&quot;。#}
            {#如果要发送DOM树信息或者其他不希望转换的信息,请设置为false#}
            success: function(data) {
                 if (data.code == 200) {
                     alert("success")
                 }
            },
            error: function() {
                  //失败
                alert("fail ")
            }
          })
    }
    
    
    </script>
    
    
    </html>
    ajax发送文件数据
    @addinfo.route("/add/picture",methods = ["POST","GET"])
    def add_picture():
        if request.method == "POST":
            picture1 = request.files.get("img")
            pic_filename = picture1.filename
            pic_filename_list = pic_filename.split(".")
            pic_filename_list[0] = pic_filename_list[0] + str(int(time.time()))
            pic_filename = ".".join(pic_filename_list)
    
            path = basepath + "/static"
            upload_path = os.path.join(path, pic_filename)
            picture1.save(upload_path)
            message= {
                "code":200
            }
    
            return jsonify(message)
        else:
            message = {
                "code": 500
            }
            return jsonify(message)
    后端获取数据

    3.ajax分页

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>展示</title>
        <script type="text/javascript" src="/static/js/jquery-1.12.4.min.js"></script>
        <script type="text/javascript" src="/static/js/jquery.pagination.min.js"></script>
    
    </head>
    <body>
    
    <table border="1" cellspacing="0">
        <div>
        <tr>
            <td>用户名</td>
            <td>邮箱</td>
            <td>手机号</td>
            <td>身高</td>
            <td>图片</td>
            <td>操作</td>
        </tr>
    
        {% for user in users %}
    
            <tr>
                <td>{{ user.name }}</td>
                <td>{{ user.email }}</td>
                <td>{{ user.phone }}</td>
                <td>{{ user.height }}</td>
                <td><img src="{{ url_for('static', filename= user.pic_name) }}" width="400" height="400" alt="图片加载失败 "></td>
    
                <td>
                    <a href="">编辑</a>
                    <a href="">删除</a>
                </td>
            </tr>
        {% endfor %}
        </div>
    </table>
    
    <br>
    <br>
    
    
    <div id="pagination" class="page"></div>
    
    <script>
            // 调用父页面的方法改变菜单指示
            // window.parent.fnChangeMenu(2);
            $(function () {
                $("#pagination").pagination({
                    currentPage: {{ page }},
                    totalPage: {{ total_page }},
                    //当点击页码链接时,会执行如下函数
                    callback: function (current) {
                        //参数current表示当前链接代表的页码值
                        //不写地址表示当前地址,即当前为新闻列表地址
                        //?page=1
                        location.href='?page='+current;
                    }
                });
            });
    </script>
    </body>
    </html>
    ajax分页
    @showuser.route("/user/show")
    @check_login
    def showinfo():
    
        page = int(request.args.get('page', '1'))
        pagination = User.query.filter_by().paginate(page, 2, False)
        user_list = pagination.items
        total_page = pagination.pages
        return render_template("showinf.html",users=user_list,
            total_page=total_page,
            page=page)
    后端数据
  • 相关阅读:
    MySQL注入总结
    使用JavaScript扫描端口
    dvwa+xampp搭建显示乱码的问题:解决办法
    精读《12 个评估 JS 库你需要关心的事》
    TinyMCE上传图片word
    xhEditor上传图片word
    JAVA大文件(100G以上)的上传下载实现技术
    JAVA大文件(1G以上)的上传下载实现技术
    java 支持 超大上G,多附件上传问题
    java 支持 超大上G,多附件上传方法
  • 原文地址:https://www.cnblogs.com/ppzhang/p/11796107.html
Copyright © 2011-2022 走看看