main.js

function uuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

/**
 * 自定义请求
 * @param option{{method:string, async: boolean,data:{},success: success, contentType: string, url: string}}
 */
function httpClient(option){

    option.method = option.method !== undefined ? option.method : "POST"
    option.async = option.async !== undefined ? option.async : false
    option.contentType = option.contentType !== undefined ? option.contentType : "application/json"
    option.data = option.data !== undefined ? option.data : {}
    option.success = option.success !== undefined ? option.success : function (result){}

    const xhr = new XMLHttpRequest();
    xhr.open(option.method, option.url, option.async);
    xhr.setRequestHeader("Content-type", option.contentType);
    xhr.onload = function (){
        if (xhr.readyState === 4 && xhr.status === 200) {
            option.success(JSON.parse(xhr.response))
        }
    }
    xhr.send(JSON.stringify(option.data));
}

/**
 * 获取地址栏属性
 * @param name
 * @returns {string|null}
 */
function getUrlParam(name) {
    const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    const r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}


/**
 * 模态提示框 基于bootstrap
 * @param msg
 */
function $alert(msg,method){
    let modalId = uuid();
    let footerHtml = method === undefined ? `<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">确定</button>` :
        `<button type="button" id="${modalId+'_footer_primary'}" class="btn btn-primary">确定</button>
         <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>`

    let modalHtml = `
<div class="modal" tabindex="-1" id="${modalId}">
  <div class="modal-dialog modal-dialog-centered modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">提示</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p>${msg}</p>
      </div>
      <div class="modal-footer">${footerHtml}</div>
    </div>
  </div>
</div>
    `

    document.getElementsByTagName("body").item(0).insertAdjacentHTML('beforeend',modalHtml)

    const myModal = new bootstrap.Modal(document.getElementById(modalId), {
        backdrop: "static"
    });
    myModal.show()
    document.getElementById(modalId).addEventListener('hidden.bs.modal', function (event) {
        document.getElementById(modalId).remove()
    })
    if(method !== undefined){
        document.getElementById(modalId+'_footer_primary').addEventListener("click",method)
        document.getElementById(modalId+'_footer_primary').addEventListener("click",function (){
            myModal.hide()
        })
    }

}

/**
 * 获取form数据 基于label for ==> id
 * @param id
 * @returns {{}}
 */
function getFormDataAsLabel(id){
    let formData = {
    }
    let elementsByTagName = document.getElementById(id).getElementsByTagName('label');
    for(let index = 0 ; index < elementsByTagName.length ; index++ ){
        let key = elementsByTagName.item(index).getAttribute("for");
        formData[key] = document.getElementById(key).value
    }
    return formData

}

/**
 * 数据写入form 基于label for ==> id
 * @param id
 * @param data
 */
function setFormDataAsLabel(id,data){
    let elementsByTagName = document.getElementById(id).getElementsByTagName('label');
    for(let index = 0 ; index < elementsByTagName.length ; index++ ){
        let key = elementsByTagName.item(index).getAttribute("for");
        document.getElementById(key).value = data[key]
    }
}

/**
 * 校验form 必填 基于label for ==> id
 * @param id
 * @returns {{isTrue: boolean, notNull: *[]}}
 */
function checkForm(id){

    let result = {isTrue:true,notNull:[]}
    let elementsByTagName = document.getElementById(id).getElementsByTagName('label');
    for(let index = 0 ; index < elementsByTagName.length ; index++ ){
        let key = elementsByTagName.item(index).getAttribute("for");
        if( document.getElementById(key).getAttribute("required") === '' &&  document.getElementById(key).value === ''){
            result.isTrue = false
            result.notNull.push({id:key})
        }
    }
    return result
}

/**
 * 模态上传框 基于bootstrap
 * @param method
 */
function $upload(method){
    let id = uuid();
    let uploadModalHtml = `
<div class="modal" id="${id}uploadFile" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-dark text-white">
                <h5 class="modal-title" >上传</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body bg-dark text-white">
                <div class="input-group mb-3">
                    <input type="file" class="form-control" placeholder="选择上传文件"  aria-describedby="${id}modalFile" id="${id}modalFile" accept=".jpg,.png">
                    <button class="btn btn-outline-danger" type="button" id="${id}modalFileButton">上传</button>
                </div>
            </div>
            <div class="modal-footer bg-dark text-white">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
    `
    document.getElementsByTagName("body").item(0).insertAdjacentHTML("beforeend",uploadModalHtml)

    const uploadFileModal = new bootstrap.Modal(document.getElementById(id+"uploadFile"), {
        backdrop: "static"
    });

    uploadFileModal.show()

    document.getElementById(id+"uploadFile").addEventListener('hidden.bs.modal', function (event) {
        document.getElementById(id+"uploadFile").remove()
    })

    document.getElementById(id+"modalFileButton").addEventListener('click', function (event) {
        if(document.getElementById(id+"modalFile").files.length === 0){
            $alert("请选择文件")
            return;
        }
        const xhr = new XMLHttpRequest();
        let formData = new FormData();
        formData.append("file",document.getElementById(id+"modalFile").files[0])
        xhr.open("POST", "/file/upload", false);
        xhr.onload = function (){
            if (xhr.readyState === 4 && xhr.status === 200) {
                let result = JSON.parse(xhr.response);
                method(result)
            }
        }
        xhr.send(formData);
    })

}





posted @ 2022-11-02 00:15  小猫会发光  阅读(43)  评论(0)    收藏  举报