简体   繁体   中英

Passing data from a form value to ajax call (Javascript)

This may seem like a nub question. I'll be the first to admit my knowledge of JavaScript is limited, I'm very desperately trying to learn, though. I'm having a bit of trouble when attempting to pass data to an additional field.

$(function () {
    $('#upload_file').submit(function (e) {
        e.preventDefault();
        $.ajaxFileUpload({
            url: './upload/upload_file/',
            secureuri: false,
            fileElementId: 'userfile',
            dataType: 'json',
            data: {
                'title': $('#title').val()
            },
            success: function (data, status) {
                if (data.status != 'error') {
                    $('#files').html('<p>Reloading files...</p>');
                    refresh_files();
                    $('#title').val('');
                }
                alert(data.msg);
            }
        });
        return false;
    });
});   

As you can see above, I'm passing across the title value in the data parameter of the AJAX call. This is successful. The question is, how would I go about passin additional forum values within the data param?

Just separate the next values with commas.

data : {
        title : $('#title').val(),
        name : "hi",
        message : "I'm another param"
},

An easy way to grab all form values is like this:

data: $('#my-form').serialize()

Works pretty well for me in most cases, unless I only want to grab specific values. You can read more about it here: http://api.jquery.com/serialize/

Either way, the above answer is probably what you want, I just thought I'd throw in a quick tip. I was pretty pumped when I first figured this out :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM