将数组附加到 FormData 并通过 AJAX 发送 [英] appending array to FormData and send via AJAX
本文介绍了将数组附加到 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 DB 中.
then 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 端,arr
变量,它是一个数组,显示为字符串.
But on the PHP side, the arr
variable, which is an array appears as a string.
当我不使用 ajax 作为表单数据发送它而是使用简单的 $.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']);
或者使用@Curios的方法
通过FormData
发送一个数组.
JS
// Use <#> or any other delimiter you want
var serial_arr = arr.join("<#>");
PHP
$arr = explode("<#>", $_POST['arr']);
这篇关于将数组附加到 FormData 并通过 AJAX 发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文