如何使用jquery序列化进行文件上传 [英] how to do file upload using jquery serialization

查看:38
本文介绍了如何使用jquery序列化进行文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个表单,我正在使用 jquery 序列化功能通过 ajax 提交表单

So I have a form and I'm submitting the form through ajax using jquery serialization function

        serialized = $(Forms).serialize();

        $.ajax({

        type        : "POST",
        cache   : false,
        url     : "blah",
        data        : serialized,
        success: function(data) {

        }

但是如果表单有一个 <input type="file"> 字段怎么办....我如何使用这个 ajax 序列化方法将文件传递到表单中...打印 $_FILES 不输出任何内容

but then what if the form has an <input type="file"> field....how do I pass the file into the form using this ajax serialization method...printing $_FILES doesn't output anything

推荐答案

无法使用 AJAX 上传文件,因为您无法访问存储在客户端计算机上的文件内容并使用 javascript 在请求中发送它.实现此目的的技术之一是使用隐藏的 iframe.有一个很好的 jquery 表单插件,它允许您对表单进行 AJAX 化,并且它 也支持文件上传.因此,使用此插件,您的代码将如下所示:

A file cannot be uploaded using AJAX because you cannot access the contents of a file stored on the client computer and send it in the request using javascript. One of the techniques to achieve this is to use hidden iframes. There's a nice jquery form plugin which allows you to AJAXify your forms and it supports file uploads as well. So using this plugin your code will simply look like this:

$(function() {
    $('#ifoftheform').ajaxForm(function(result) {
        alert('the form was successfully processed');
    });
});

插件自动负责订阅表单的 submit 事件,取消默认提交,序列化值,使用正确的方法和处理文件上传字段,...

The plugin automatically takes care of subscribing to the submit event of the form, canceling the default submission, serializing the values, using the proper method and handle file upload fields, ...

这篇关于如何使用jquery序列化进行文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆