js实现的模拟form提交数据

三月的最后一天,再来发篇博文,由于需要使用window.open的方式去访问URL,但是所需要传递的参数比较多,window.open默认使用的是get方式提交数据,这使开发很不爽。

在别人的指导下,在js中模拟form提交也是一个不错的想法,但是很尴尬,我用jQuery实现的form提交不能够请求到后台,以下是我写的代码,

 	 var form = $('<form>');
         form.attr("action",url);
         form.attr("target","_blank");
         form.attr("method","post");
         form.append('<input type="hidden" name="form.noteForm" value="'+data+'">');
         form.submit();

然而却没什么卵用,请求不到后台,然后同事用原生js写的方法如下,

	/**
	 * 导出excel使用的post
	 */
	post : function(URL, PARAMS) {
		var temp = document.createElement("form");
		temp.action = URL;
		temp.method = "post";
		temp.style.display = "none";
		if (PARAMS.length > 0) {
			for (var i = 0; i < PARAMS.length; i++) {
				var opt = document.createElement("textarea");
				opt.name = PARAMS[i].name;
				//防止IE浏览器将null 自动转换为"null" 导致错误
				if(PARAMS[i].value !== null){
					opt.value = PARAMS[i].value;
				}
				temp.appendChild(opt);
			}
		}
		document.body.appendChild(temp);
		temp.submit();
		return temp;
	}
};

为了我自己使用方便,我修改成了如下,

post : function(URL, PARAMS) {
        var temp = document.createElement("form");
        temp.action = URL;
        temp.method = "post";
        temp.style.display = "none";
        var hideInput = document.createElement("input");
        hideInput.type="hidden";
        //传入参数名,相当于get请求中的content=
        hideInput.name= "content";
        //传入数据,只传递了一个参数内容,实际可传递多个。
        hideInput.value= PARAMS;
        temp.appendChild(hideInput);
        document.body.appendChild(temp);
        temp.submit();
        return temp;
    },

URL是所要请求的URL,params是所要传递的参数。

如果哪位大神看到知道原因的,请指教。。。。。

猜你喜欢

转载自blog.csdn.net/wojiaohuangyu/article/details/68921391