ajax将文件和变量发送到php

时间:2014-01-19 04:37:32

标签: php ajax file jquery upload

我正在使用ajax调用来上传由PHP处理的文件。应根据jquery变量将文件放在特定目录中。我可以上传文件,但无法将变量与文件一起传递。 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
    }
});     

我尝试将data属性更改为“fd +'& myVar ='+ myVar,但是PHP无法正确解析数据并为$ _FILES ['file']变量以及$ _POST返回未定义的索引错误['myVar']变量。

如何发送文件和变量?

3 个答案:

答案 0 :(得分:6)

如果您需要其他表单字段,请再次调用fd.append:

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

答案 1 :(得分:4)

除了filedata对象的文件之外,您可以append

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
    }
});     

答案 2 :(得分:-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
    }
});