Jquery动态构建form

WEB开发 | 2015-11-13 16:32:45 | 阅读 3132 次 | 评论(0)
jQuery(function ($) {
	$.extend({
		form: function (url, data, method) {
			if (method == null) method = 'POST';
			if (data == null) data = {};

			var form = $('<form>').attr({
				method: method,
				action: url
			}).css({
				display: 'none'
			});

			var addData = function (name, data) {
				if ($.isArray(data)) {
					for (var i = 0; i < data.length; i++) {
						var value = data[i];
						addData(name + '[]', value);
					}
				} else if (typeof data === 'object') {
					for (var key in data) {
						if (data.hasOwnProperty(key)) {
							addData(name + '[' + key + ']', data[key]);
						}
					}
				} else if (data != null) {
					form.append($('<input>').attr({
						type: 'hidden',
						name: String(name),
						value: String(data)
					}));
				}
			};

			for (var key in data) {
				if (data.hasOwnProperty(key)) {
					addData(key, data[key]);
				}
			}

			return form.appendTo('body');
		}
	});
});

调用方式:

$.form('xxxurl', $json, 'POST').submit();

文章评论,共0条
游客请输入验证码
浏览1695421次
文章归档
最新评论