ajax与后台交互案例

BBS项目

		//BBS项目,注册页面ajax请求
        // 1.实现照片预览 
    $("#up_myhead").change(function () {
        // 获取input选择的文件
        let file_obj = $(this)[0].files[0];
        // 为该图片准备一个文件阅读器
        let read = new FileReader();
        // Starts reading the contents of the specified Blob, once finished, the result attribute contains a data: URL representing the file's data.
        // asynchronously read the contents of files
        read.readAsDataURL(file_obj);
        read.onload = function (event) {
            // 把获取到的传给img
            document.querySelector("#head_img").src = read.result
        }
    });
	// ajax提交注册
    $("#btn_submit").click(function () {
        // 生成提交对象
        let form_data = new FormData();
        let sub = $("#form_reg").serializeArray();
        $.each(sub, function (index, val) {
            form_data.append(val.name, val.value)
        });
        form_data.append("myfile", $("#up_myhead")[0].files[0]);
        console.log('留空1');
        $.ajax({
            url: "/register/",
            type: "post",
            contentType: false, //告诉jQuery不要去设置Content-Type请求头
            processData: false, //告诉jQuery不要去处理发送的数据
            data: form_data,
            success: function (data) {
                if (data.status == 100) {
                    window.location.href = '/login/'
                } else {
                    $.each(data.msg, function (index, val) {
                        $("#id_" + index).next().text(val).parent().addClass("has-error");
                        // 提示两次密码不一致
                        if (index == "__all__") {
                            $("#id_re_pwd").next().text(val).parent().addClass("has-error");
                        }
                    });
                    // 三秒后清除错误提示和error效果
                    setTimeout(function () {
                        let form = $(".form-group");
                        form.removeClass("has-error").children("span").empty();
                        form.children("input").val("");
                    }, 3000)
                }
            }
        })
    });
posted @ 2019-02-28 08:31  甜麦地  阅读(575)  评论(0编辑  收藏  举报