2014-01-19 130 views
1

我正在使用ajax调用来上传PHP处理的文件。该文件应该放置在基于jQuery变量的特定目录中。我可以获取要上传的文件,但不能将该变量与文件一起传递。 PHP报告一个未定义的索引错误。ajax发送文件和变量到php

Ajax代码:

var fd = new FormData();  
fd.append('file', document.getElementById('select').files[0]); 
$.ajax({ 
    url: 'test.php', 
    type: 'POST', 
    data: fd, 
    processData: false, 
    contentType: false, 
    success: function(e){ 
     // some code here 
    } 
});  

我试图改变数据属性设置为“FD +” & myVar的= '+ myVar的,但是PHP不能正确解析数据并返回undefined指数误差均$ _FILES ['文件“]变量还有$ _ POST [” myVar的']变量。

我怎么能同时发送的文件和变量?

回答

6

如果您需要另一个表单字段,调用fd.append第二次:

fd.append('file', document.getElementById('select').files[0]); 
fd.append('myVar',myVar); 
4

您可以append值比文件到FORMDATA对象等。

var fd = new FormData();  
fd.append('file', document.getElementById('select').files[0]); 
fd.append('myVar', myVar); 
$.ajax({ 
    url: 'test.php', 
    type: 'POST', 
    data: fd, 
    processData: false, 
    contentType: false, 
    success: function(e){ 
     // some code here 
    } 
});  
-1

参考$.ajax jQuery的API文档。

明确指出,data应该是一个对象,其键值对代表服务器端脚本接受的数据。无论如何,不​​知道为什么jQuery似乎不接受你的数据。也许你应该手动尝试这个。

由于您test.php接受POST数据myVar您的jQuery的Ajax的配置或许应该像

$.ajax({ 
    url: 'test.php', 
    type: 'POST', 
    data: { 
     myVar: document.getElementById('select').files[0] 
    }, 
    success: function(e){ 
    // some code here 
    } 
});