js模拟from表单提交

直接奉上代码

/**
 * Created by alterego on 2018/6/10.
 */

/**
 * 将url以表单的方式提交
 * @param url 提交地址
 * @param paramArray 提交参数,数组类型 例:[{"name":"张三"},{"age":"14"}]
 */
var postFromSubmitParamArray = function (url, paramArray,target) {
    var postUrl = url;//提交地址
    var ExportForm = document.createElement("FORM");
    document.body.appendChild(ExportForm);
    ExportForm.method = "POST";
    if(target&&(target=="_blank"||target=="_blank"||target=="_parent"||target=="_self"||target=="_top")){
        ExportForm.target = target;
    }
    for (var i = 0; i < paramArray.length; i++) {
        var newElement = document.createElement("input");
        newElement.setAttribute("name", paramArray[i].key);
        newElement.setAttribute("type", "hidden");
        ExportForm.appendChild(newElement);
        newElement.value = paramArray[i].value;
    }
    ExportForm.action = postUrl;
    ExportForm.submit();
};
/**
 * 将url以表单的方式提交
 * @param url 提交地址
 * @param paramMap 提交参数,map类型
 */
var postFromSubmitParamMap = function (url, paramMap,target) {
    var postUrl = url;
    var ExportForm = document.createElement("FORM");
    document.body.appendChild(ExportForm);
    ExportForm.method = "POST";
    if(target&&(target=="_blank"||target=="_blank"||target=="_parent"||target=="_self"||target=="_top")){
        ExportForm.target = target;
    }
    for (var key in paramMap) {
        var newElement = document.createElement("input");
        newElement.setAttribute("name", key);
        newElement.setAttribute("type", "hidden");
        ExportForm.appendChild(newElement);
        newElement.value = paramMap[key];
    }
    ExportForm.action = postUrl;
    ExportForm.submit();
};
/**
 * 将url以表单的方式提交
 * @param url url里面带有参数
 */
var postFromSubmit = function (url,target) {
    var paramArray = new Array();
    var postUrl = url;
    if (url.indexOf("?") != -1) {
        postUrl = url.substring(0,url.indexOf("?"))
        var str = url.substring(url.indexOf("?")+1,url.length);
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            var input = {};
            input.key = strs[i].split("=")[0];
            input.value = strs[i].split("=")[1];
            paramArray.push(input)
        }
    }
    postFromSubmitParamArray(postUrl, paramArray,target);
};

如果不需要在新窗口打开“target”可以不用传,在新窗口打开“target”传“_blank”

还有测试代码




    
    Title
    
    







你可能感兴趣的:(web前端)