dtuzjzs3853 2015-06-12 07:52
浏览 42
已采纳

Jquery使用一个ajax调用发布文件和数据

Hi I have a wordpress php class that receives my ajax and works good. Now i have to upload a file in the same POST request i use to pass parameters to the PHP class ( i have a switch in the class that sends me to the proper function based on the parameters in the POST data ).

this is the code:

$(document).ready(function (e) {


$('#imageUploadForm').on('submit',(function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    var userID = <?php echo get_current_user_id(); ?>; 
    var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    var data = {
            'action': 'romme_call',
            'whatever': 1234, 
            'userID': userID,
            'function_call': 'upload_profile_photo',
            **'form_data' : formData**
        };
         console.log(data);
        jQuery.post(ajaxurl, data, function(response) {
            console.log("done");
            console.log(data);
        });

this code will of course return a "Uncaught TypeError: Illegal invocation"

because it does not accept formData as parameter in data.

how can i handle this?

  • 写回答

1条回答 默认 最新

  • dongwu9647 2015-06-12 08:02
    关注

    It returns Illegal invocation because jQuery is trying to parse the form data with $.param.

    When submitting files with jQuery's ajax processing must be turned off

    $('#imageUploadForm').on('submit', (function (e) {
        e.preventDefault();
        var formData = new FormData(this);
        var userID = <? php echo get_current_user_id(); ?> ;
        var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    
        formData.append('action', 'romme_call');
        formData.append('whatever', '1234');
        formData.append('userID', userID);
        formData.append('function_call', 'upload_profile_photo');
    
        $.ajax({
            url  : ajaxurl,
            type : 'POST',
            data : formData,
            contentType: false,
            processData: false
        }).done(function(response) {
            console.log("done");
            console.log(data);
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有卷积神经网络识别害虫的项目吗
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件