Jquery动态构建form

WEB开发 | 2015-11-13 16:32:45 | 2466次阅读 | 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条
浏览1431587次