追加数组FORMDATA和发送通过AJAX [英] appending array to FormData and send via AJAX

查看:601
本文介绍了追加数组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']);

这篇关于追加数组FORMDATA和发送通过AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆