使用jQuery的“Form Plugin”上传Ajax文件

时间:2022-12-09 19:48:28

I am using jQuery, and I would like to upload files with Ajax. I have made some searches and found it is not possible.

我正在使用jQuery,我想用Ajax上传文件。我做了一些搜索,发现它是不可能的。

However, there is one jQuery plugin, jQuery Form Plugin, which allows us to upload files through Ajax.

但是,有一个jQuery插件,jQuery Form Plugin,它允许我们通过Ajax上传文件。

It works very well, but I have a special problem. Here is my code:

它工作得很好,但我有一个特殊的问题。这是我的代码:

$('#question-form').submit(function() {
    var serialAnswers = '';

    // Create a query string given some fields
    // Format of the query string : answers[0][fr_fr][0]=a1fr&answers[0][fr_fr][1]=2&answers[0][en_uk][0]=a1en&answers[0][en_uk][1]=6&...
    $('#question-answers > div').each(function(idx, elt) {
        $('div[lang]', $(elt)).each(function(idxLang, eltLang) {
            var lang = $(this).attr('lang');
            serialAnswers += 'answers[' + idx + '][' + lang + '][0]=' + $("[answerpart=display]", $(eltLang)).val();
            serialAnswers += '&answers[' + idx + '][' + lang + '][1]=' + $("[answerpart=value]", $(eltLang)).val() + '&';
        });
    });

    $(this).ajaxSubmit({
        datatype: "html",
        type: "POST",
        data: serialAnswers,
        url: $(this).attr("action"),
        success: function(retour) {
            $('#res-ajax').html(retour);
        }
    });

    return false;
});

As you can see, I have to replace the $.ajax call by a $(this).ajaxSubmit() call, with the same options. Moreover, I have to create a query string (serialAnswers in the code) according to some fields in order to transmit it to the PHP code.

正如您所看到的,我必须用$(this).ajaxSubmit()调用替换$ .ajax调用,并使用相同的选项。此外,我必须根据某些字段创建一个查询字符串(代码中的serialAnswers),以便将其传输到PHP代码。

Here is what I used to do when I had no file to upload. I just serialized the form fields and added my query string named serialAnswers:

这是我以前没有文件上传的过去。我只是序列化了表单字段并添加了名为serialAnswers的查询字符串:

$.ajax({
    datatype: "html",
    type: "POST",
    data: $(this).serialize() + '&' + serialAnswers,
    url: $(this).attr("action")
    success: function(retour) {
        $("#res-ajax").html(retour);
    }
});

But my problem is that the form plugin transmits my additional data (the query string) that way (in the PHP file):

但我的问题是表单插件以这种方式传输我的附加数据(查询字符串)(在PHP文件中):

Array
(
    [question_heading_fr_fr] => something
    [question_heading_en_uk] => nothing
    [question_type] => 5
    [0] => a
    [1] => n
    [2] => s
    [3] => w
    [4] => e
    [5] => r
    [6] => s
    [7] => [
    [8] => 0
    [9] => ]
    [10] => [
    [11] => f
    [12] => r
    [13] => _
    [14] => f
    [15] => r
    [16] => ]
    ....
)

According to the documentation, I have to pass a JSON object to the data option, like this:

根据文档,我必须将JSON对象传递给data选项,如下所示:

data: { key1: 'value1', key2: 'value2' }

But I don't know how to convert my query string to a JSON object and if it would be interpreted as an array on the PHP side.

但我不知道如何将我的查询字符串转换为JSON对象,如果它将被解释为PHP端的数组。

Is there a solution?

有解决方案吗?

EDIT: Even if I use an iframe, I don't know how to add a query string with information which does not come from the form (my serialAnswer from the code above).

编辑:即使我使用iframe,我也不知道如何添加一个查询字符串,其中的信息不是来自表单(我的serialAnswer来自上面的代码)。

3 个解决方案

#1


0  

Try Uploadify. This is a Flash based upload plugin. It is easy to implement and supports multiple file upload.

试试Uploadify。这是一个基于Flash的上传插件。它易于实现并支持多文件上传。

#2


0  

I'm not sure exactly what your looking for but why can't you just do:

我不确定你在寻找什么,但为什么你不能这样做:

data: {'key1':$(this).serialize(),'key2': serialAnswers}

Then on the PHP side to decode PHP you do

然后在PHP端解码PHP你做的

json_decode($arr); //Where $arr is whatever the array is that gets passed

If you need to pass back a JSON response you just do:

如果您需要传回JSON响应,您只需执行以下操作:

json_encode($arr); //Where arr is an array you build within your script

I'm assuming this is what you want.

我假设这是你想要的。

#3


0  

EDIT: I found a new solution, and it works :)

编辑:我发现了一个新的解决方案,它的工作原理:)

I have modified the jQuery Form Plugin. Plugin page: http://jquery.malsup.com/form/#getting-started. Script: https://github.com/malsup/form/raw/master/jquery.form.js

我修改了jQuery Form Plugin。插件页面:http://jquery.malsup.com/form/#getting-started。脚本:https://github.com/malsup/form/raw/master/jquery.form.js

In order to use this syntax:

要使用此语法:

$('#myform').submit(function() {
    var queryString = 'answers[0][fr_fr][0]=a1fr&answers[0][fr_fr][1]=2&answers[0][en_uk][0]=a1en&answers[0][en_uk][1]=6';

    $(this).ajaxSubmit({
        dataType:  'html',
        data: queryString
    });

    return false; 
});

instead of:

代替:

$('#myform').submit(function() {
    $(this).ajaxSubmit({
        dataType:  'html',
        data: {'key':'value' }
    });

    return false; 
});

I have modified the plugin code.

我修改了插件代码。

Find this:

找到这个:

var n,v,a = this.formToArray(options.semantic);
if (options.data) {
    options.extraData = options.data;
    for (n in options.data) {
        if(options.data[n] instanceof Array) {
            for (var k in options.data[n]) {
                a.push( { name: n, value: options.data[n][k] } );
            }
        }
        else {
            v = options.data[n];
            v = $.isFunction(v) ? v() : v; // if value is fn, invoke it
            a.push( { name: n, value: v } );
        }
    }
}

And delete all the if (options.data) and its content. A few lines after these ones, find this:

并删除所有if(options.data)及其内容。在这些之后的几行,找到这个:

var q = $.param(a);

And add this right after it:

然后在它之后添加:

if (options.data) {
    options.extraData = options.data;
    q += '&' + options.data;
}

In the function fileUpload(), find this:

在函数fileUpload()中,找到这个:

var extraInputs = [];
try {
    if (s.extraData) {
        for (var n in s.extraData) {
            extraInputs.push(
                $('<input type="hidden" name="'+n+'" value="'+s.extraData[n]+'" />')
                    .appendTo(form)[0]);
        }
    }

    // Add iframe to doc and submit the form
    $io.appendTo('body');
    io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
    form.submit();
}

And replace it by:

并替换为:

var extraInputs = [];
try {
    if (s.extraData) {
        var couples = s.extraData.split('&');
        for (var c=0 ; c < couples.length ; c++)
        {
            var couple = couples[c].split('=');
            extraInputs.push(
                $('<input type="hidden" name="'+couple[0]+'" value="'+couple[1]+'" />')
                    .appendTo(form)[0]);
        }
    }

    // add iframe to doc and submit the form
    $io.appendTo('body');
    io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
    form.submit();
}

You now can add a query string thanks to these modifications and uploading an image at the same time.

您现在可以通过这些修改添加查询字符串并同时上传图像。

#1


0  

Try Uploadify. This is a Flash based upload plugin. It is easy to implement and supports multiple file upload.

试试Uploadify。这是一个基于Flash的上传插件。它易于实现并支持多文件上传。

#2


0  

I'm not sure exactly what your looking for but why can't you just do:

我不确定你在寻找什么,但为什么你不能这样做:

data: {'key1':$(this).serialize(),'key2': serialAnswers}

Then on the PHP side to decode PHP you do

然后在PHP端解码PHP你做的

json_decode($arr); //Where $arr is whatever the array is that gets passed

If you need to pass back a JSON response you just do:

如果您需要传回JSON响应,您只需执行以下操作:

json_encode($arr); //Where arr is an array you build within your script

I'm assuming this is what you want.

我假设这是你想要的。

#3


0  

EDIT: I found a new solution, and it works :)

编辑:我发现了一个新的解决方案,它的工作原理:)

I have modified the jQuery Form Plugin. Plugin page: http://jquery.malsup.com/form/#getting-started. Script: https://github.com/malsup/form/raw/master/jquery.form.js

我修改了jQuery Form Plugin。插件页面:http://jquery.malsup.com/form/#getting-started。脚本:https://github.com/malsup/form/raw/master/jquery.form.js

In order to use this syntax:

要使用此语法:

$('#myform').submit(function() {
    var queryString = 'answers[0][fr_fr][0]=a1fr&answers[0][fr_fr][1]=2&answers[0][en_uk][0]=a1en&answers[0][en_uk][1]=6';

    $(this).ajaxSubmit({
        dataType:  'html',
        data: queryString
    });

    return false; 
});

instead of:

代替:

$('#myform').submit(function() {
    $(this).ajaxSubmit({
        dataType:  'html',
        data: {'key':'value' }
    });

    return false; 
});

I have modified the plugin code.

我修改了插件代码。

Find this:

找到这个:

var n,v,a = this.formToArray(options.semantic);
if (options.data) {
    options.extraData = options.data;
    for (n in options.data) {
        if(options.data[n] instanceof Array) {
            for (var k in options.data[n]) {
                a.push( { name: n, value: options.data[n][k] } );
            }
        }
        else {
            v = options.data[n];
            v = $.isFunction(v) ? v() : v; // if value is fn, invoke it
            a.push( { name: n, value: v } );
        }
    }
}

And delete all the if (options.data) and its content. A few lines after these ones, find this:

并删除所有if(options.data)及其内容。在这些之后的几行,找到这个:

var q = $.param(a);

And add this right after it:

然后在它之后添加:

if (options.data) {
    options.extraData = options.data;
    q += '&' + options.data;
}

In the function fileUpload(), find this:

在函数fileUpload()中,找到这个:

var extraInputs = [];
try {
    if (s.extraData) {
        for (var n in s.extraData) {
            extraInputs.push(
                $('<input type="hidden" name="'+n+'" value="'+s.extraData[n]+'" />')
                    .appendTo(form)[0]);
        }
    }

    // Add iframe to doc and submit the form
    $io.appendTo('body');
    io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
    form.submit();
}

And replace it by:

并替换为:

var extraInputs = [];
try {
    if (s.extraData) {
        var couples = s.extraData.split('&');
        for (var c=0 ; c < couples.length ; c++)
        {
            var couple = couples[c].split('=');
            extraInputs.push(
                $('<input type="hidden" name="'+couple[0]+'" value="'+couple[1]+'" />')
                    .appendTo(form)[0]);
        }
    }

    // add iframe to doc and submit the form
    $io.appendTo('body');
    io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
    form.submit();
}

You now can add a query string thanks to these modifications and uploading an image at the same time.

您现在可以通过这些修改添加查询字符串并同时上传图像。