追加数组FORMDATA和发送通过AJAX
问题描述:
我用ajax提交与阵列,文本字段和文件的多部分的形式。
I'm using ajax to submit a multipart form with array, text fields and files.
我每次追加VAR的主要数据为这样
I append each VAR to the main data as so
var attachments = document.getElementById('files');
var data= new FormData();
for (i=0; i< attachments.files.length; i++){
data.append('file', attachments.files[i]);
console.log(attachments.files[i]);
data.append ('headline', headline);
data.append ('article', article);
data.append ('arr', arr);
data.append ('tag', tag);
比我使用AJAX功能,将其发送到一个PHP文件来存储SQL数据库里面。
than I use the ajax function to send it to a PHP file to store inside sql DB.
$.ajax({
type: "post",
url: 'php/submittionform.php',
cache: false,
processData: false,
contentType: false,
data: data,
success: function(request) {$('#box').html(request); }
})
但在PHP端时,改编
变量,它是一个数组显示为一个字符串。
But on the PHP side, the arr
variable, which is an array appears as a string.
当我不为表数据与阿贾克斯发送,但使用简单的 $。POST
选项我得到它作为在PHP端阵列,但随后我不能发送的文件。
When I don't send it with ajax as Form data but use the simple $.POST
option I do get it as an array on the PHP side, but then I can't send the files as well.
任何解决方案?
答
您可以做两件事情:
JS
var json_arr = JSON.stringify(arr);
PHP
$arr = json_decode($_POST['arr']);
2。序列化的数据,然后反序列化在PHP
JS
// Use <#> or any other delimiter you want
var serial_arr = arr.join("<#>");
PHP
$arr = explode("<#>", $_POST['arr']);