Uploading both data and files in one form using Ajax?

后端 未结 10 847
无人共我
无人共我 2020-11-21 05:48

I\'m using jQuery and Ajax for my forms to submit data and files but I\'m not sure how to send both data and files in one form?

I currently do almost the same with b

10条回答
  •  遇见更好的自我
    2020-11-21 06:31

    another option is to use an iframe and set the form's target to it.

    you may try this (it uses jQuery):

    function ajax_form($form, on_complete)
    {
        var iframe;
    
        if (!$form.attr('target'))
        {
            //create a unique iframe for the form
            iframe = $("").attr('name', 'ajax_form_' + Math.floor(Math.random() * 999999)).hide().appendTo($('body'));
            $form.attr('target', iframe.attr('name'));
        }
    
        if (on_complete)
        {
            iframe = iframe || $('iframe[name="' + $form.attr('target') + '"]');
            iframe.load(function ()
            {
                //get the server response
                var response = iframe.contents().find('body').text();
                on_complete(response);
            });
        }
    }
    

    it works well with all browsers, you don't need to serialize or prepare the data. one down side is that you can't monitor the progress.

    also, at least for chrome, the request will not appear in the "xhr" tab of the developer tools but under "doc"

提交回复
热议问题