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, "accept-charset" : "utf-8", // 重要,解决其余浏览器 onsubmit : "document.charset='utf-8';" //重要,解决IE提交时编码问题 }).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'); } }); });
使用示例:javascript
$.form('/index').submit(); <form action="/index" method="POST"></form>
$.form('/new', { title: 'Hello World', body: 'Foo Bar' }).submit(); <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').submit(); <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] }).submit(); <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>
// 当前页建立form var formName = 'zzz'; var $form = $.form('http://xxx', data, "post", formName); // 打开新窗口 var obj = window.open("about:blank"); // 将当前页建立的form放到新窗口 obj.document.write($form.prop("outerHTML")); // 新窗口加上表单提交脚本 var script2 = '<script>document.' + formName + '.submit();</script>'; // 将表单提交脚本放到新窗口,新窗口执行表单提交 obj.document.write(script2); // 移除当前页form $form.remove();