[英]Add data into multi-dimentional array with javascript
[File
{ size=295816, type="image/jpeg", name="img_new3.JPG"},
File { size=43457, type="image/jpeg", name="nature.jpg"}
]
this is the data that i received from the script now i have to send only size and the name of the file with to the php file through ajax. 这是我从脚本接收到的数据,现在我必须仅通过ajax将大小和文件名发送到php文件。
here is my code 这是我的代码
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)
i want to access the params for my PHP file: 我想访问我的PHP文件的参数:
file(
name=>array(
0=>"name",
1=>"size"
),
size=>array(...)
)
how do i make an array that send the data to PHP file like the above? 我该如何将上述数据发送到PHP文件的数组?
First of all you have to use the Object
notation, not Array
, and then you can pass it to your PHP function via Ajax . 首先,您必须使用Object
符号,而不是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;
}
And then use that array with JSON.stringify
to pass data to your PHP script like this: 然后将该数组与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
}
});
Anyway I suggest you changing the way you store your data. 无论如何,我建议您更改存储数据的方式。 Objects are very useful in this case: 在这种情况下,对象非常有用:
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
});
}
您已经准备好js数组,因此只需使用jQuery post方法将创建的数组发送到php文件,然后该php文件将以您希望的方式处理该数组。
Your multidimensional array can be JSON encoded and sent as a string via ajax to the PHP script, which can decode the JSON back to an array/object: 您的多维数组可以进行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");
}
});
On the PHP side: 在PHP方面:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$filesArray = json_decode($_POST['myFiles']);
print_r($filesArray);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.