开发者

Get all form elements value to be attached for ajax call

I have an object that is inside of a form.

His value is assigned to an ajax call like this

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();
 }

I want to get the parent form of this element, and to loop through all inputs and add that too to the data to be used on an Ajax call.

I want the input name to be the key for the data array.

Probably something li开发者_开发问答ke:

var form = $$.parents('form:first');

and next thing to loop through the inputs and attach to data.

How to do that using jQuery?


I think you're reinventing the wheel here, there's already a .serialize() method specifically for this, like this:

var data = $(this).closest("form").serialize();

Or if you want an object representation you can loop through/add to, you can use .serializeArray() then manipulate it before passing it as the data option. It's unclear exactly what you're after, but it sounds like you just want to pass the entire form as the data argument to $.ajax() or a short-hand version, in which case .serialize() would be perfect.


Did you see.use jQuery 'Form' plugin?
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

It will do all the work for you, and will work even for file uploadas (by creating hidden iframe on the fly and submitting it). IT also can use JSON and or XML format. PRetty handy one.

See the examples
http://jquery.malsup.com/form/#tab4

Assuming the AJAX handler is st as the form target, it's as simple as:

$('#myForm1').ajaxForm();

You can also override plenty of options as well:

// 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); 
}); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜