用jquery实现post请求(非ajax)

作者在 2015-05-09 10:32:03 发布以下内容


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('/index')

<form action="/index" method="POST"></form>
$.form('/new', { title: 'Hello World', body: 'Foo Bar' })

<form action="/index" method="POST">
    <input type="hidden" name="title" value="Hello World" />
    <input type="hidden" name="body" value="Foo Bar" />
</form>
$.form('/info', { userIds: [1, 2, 3, 4] }, 'GET')

<form action="/info" method="GET">
    <input type="hidden" name="userIds[]" value="1" />
    <input type="hidden" name="userIds[]" value="2" />
    <input type="hidden" name="userIds[]" value="3" />
    <input type="hidden" name="userIds[]" value="4" />
</form>
$.form('/profile', { sender: { first: 'John', last: 'Smith', postIds: null },
                     receiver: { first: 'Foo', last: 'Bar', postIds: [1, 2] })

<form action="/profile" method="POST">
    <input type="hidden" name="sender[first]" value="John">
    <input type="hidden" name="sender[last]" value="Smith">
    <input type="hidden" name="receiver[first]" value="John">
    <input type="hidden" name="receiver[last]" value="Smith">
    <input type="hidden" name="receiver[postIds][]" value="1">
    <input type="hidden" name="receiver[postIds][]" value="2">
</form>
With jQuery's .submit() method you can create and submit a form with a simple expression:



$.form('http://stackoverflow.com/search', { q: '[ajax]' }, 'GET').submit();


WEB开发 | 阅读 3972 次
文章评论,共1条
清兒
2015-07-10 14:33
1
游客请输入验证码
浏览2893801次
文章归档
最新评论
  • 静夜思:-1是多核
  • 时光拾荒者:CtrlCV还是强的😝
  • 硬识岩丝:解决了,太感谢了~