我有一个在表单内的对象。
他的值被分配给像这样的ajax调用
var $$ = $(this);
if (typeof settings.data == 'string') {
data = settings.data + '&' + this.name + '=' + $$.val();
} else if (typeof settings.data == 'object') {
data = settings.data;
data[this.name] = $$.val();
}
我想获取此元素的父表单,并循环遍历所有输入并将其添加到要在Ajax调用上使用的数据。
我希望输入名称是数据数组的键。
可能类似于:
var form = $$.parents('form:first');
接下来要循环输入并附加到数据。
如何使用jQuery做到这一点?
答案 0 :(得分:4)
我认为你在这里重新发明轮子,已经专门为此设置了.serialize()
方法,如下所示:
var data = $(this).closest("form").serialize();
或者如果你想要一个可以遍历/添加的对象表示,你可以使用.serializeArray()
然后在将它作为数据选项传递之前对其进行操作。目前还不清楚完全你所追求的是什么,但听起来就像你只想将整个表格作为数据参数传递给$.ajax()
或{{3} },在这种情况下a short-hand version将是完美的。
答案 1 :(得分:0)
你有没有看到。使用jQuery'Form'插件?
http://www.google.com.au/search?q=jquery+form+plugin&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a
它将为您完成所有工作,甚至可以用于文件上传(通过动态创建隐藏的iframe并提交它)。 IT也可以使用JSON和/或XML格式。很方便。
参见示例
http://jquery.malsup.com/form/#tab4
假设AJAX处理程序是st作为表单目标,它就像:
一样简单$('#myForm1').ajaxForm();
你也可以覆盖很多选项:
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#output1', // target element(s) to be updated with server response
beforeSubmit: showRequestFunction, // pre-submit callback
success: showResponseFunction // post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
// bind form using 'ajaxForm'
$('#myForm1').ajaxForm(options);
});