使用数据通过$ .ajax发送的混合输入(文本和文件)

时间:2014-03-24 13:59:02

标签: javascript ajax object

我尝试将带有两个输入的数据发送到php代码,其中一个只是文本,另一个是类型文件。第二个字段也用于多个文件选择。好吧,这是html部分的代码:

        <input type="text" id="padron-documento" class="form-control input-lg" name="padron-documento" placeholder="Padrón" /><br />
        <div class="alert alert-info">
        <input type="file" id="archivos" name="archivos[]" multiple onChange="seleccionado()" />
        </div>
        <div id="cargados">
        <!-- Here we display the loaded files. -->
        </div>

好的,这是javascript部分的代码:

function seleccionado(){
var archivos = document.getElementById("archivos");//We get the value of the input with id archivos
var archivo = archivos.files; //Here we get the value of input (archivos) into an array

//Teh FormData object allow us to create a form passing to it a key/value to send it, this kind of object already have the multipart/form-data to upload files
var datos = new FormData();

padron = $("#padron-documento").val();
//We don't know how much files the user will upload, we iterate the variable
//and we pass key/value with the method append to the object FormData, we use the index "i"    // to avoid repeated values, if we not use it, it will only have the value of the last iteration
for(i=0; i<archivo.length; i++){
datos.append('archivo'+i,archivo[i]);
}

$.ajax({
url:'subir.php', //Url
type:'POST', //Method
contentType:false, //It must be false
data: {padron,datos}, //We pass the object that we already create with archivos and also the text with id padron
processData:false, //It must be false to avoid jquery processing
cache:false //Avoid to save cache
}).done(function(msg)
{$("#cargados").append(msg); //It will show the files loaded into div "cargados"});}
/*****************************/

我还有一个处理上传文件的php文件,但它的工作正常。好吧,我的麻烦在于发送&#34;数据&#34;来自$.ajax对象的属性。如何通过$.ajax对象的数据属性发送文本链(如ID号和文件),例如,我知道:data: id:idnumber,file:filearray,但我无法进行这样工作。该文件是一个文件数组,输入文本字段就是文本。有帮助吗?

0 个答案:

没有答案