0
[File 
    { size=295816, type="image/jpeg", name="img_new3.JPG"}, 
 File { size=43457, type="image/jpeg", name="nature.jpg"}
]

这是我从脚本收到的数据,现在我只需通过 ajax 将文件的大小和名称发送到 php 文件。
这是我的代码

            var files = []; 
            files["file"] = [];

            // file is an object that has the above result
            for( var i=0, j=file.length; i<j; i++ ){
                console.log( file[i].name );
                files["file"][i] = file[i].name;
                files["file"][i] = file[i].size;
            }

            // Send Request to Create ZIP File
            console.log(files)

我想访问我的 PHP 文件的参数:

file(
    name=>array(
          0=>"name", 
          1=>"size"
    ), 
    size=>array(...)
)

我如何制作一个将数据发送到上述 PHP 文件的数组?

4

3 回答 3

1

首先,您必须使用Object符号 not Array,然后您可以通过Ajax将其传递给您的 PHP 函数。

var files = {};
files["file"] = [];

// file is an object that has the above result
for (var i = 0, j = file.length; i < j; i++ ){
    console.log(file[i].name);
    files["file"][i] = file[i].name;
}

然后使用该数组JSON.stringify将数据传递给您的 PHP 脚本,如下所示:

$.ajax({
    url: "your url",
    type: "POST", //can be get also, depends on request
    cache: false, //do you want it to be cached or not?
    data: {files: JSON.stringify(files)},
    success: function(data) {
        //do something with returned data
    }
});

无论如何,我建议您更改存储数据的方式。在这种情况下,对象非常有用:

var files = [];

// file is an object that has the above result
for (var i = 0, j = file.length; i < j; i++ ){
    console.log(file[i].name);
    files.push({
        name: file[i].name //you can add all the keys you want
    });
}
于 2013-06-12T07:48:15.397 回答
0

您已准备好 js 数组,因此只需使用jQuery post 方法将创建的数组发送到 php 文件,然后以您希望的方式处理数组。

于 2013-06-12T07:43:11.330 回答
0

您的多维数组可以进行 JSON 编码,并通过 ajax 作为字符串发送到 PHP 脚本,该脚本可以将 JSON 解码回数组/对象:

// assuming the array is in files var
$.ajax({
    url : 'page.php',
    type : 'POST',
    data : { myFiles : JSON.stringify(files) },
    success : function(response){
        console.log("successfull");
    }
});

在 PHP 方面:

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $filesArray = json_decode($_POST['myFiles']);
    print_r($filesArray);
}
于 2013-06-12T07:48:48.443 回答