AJAX文件上传-类型错误:不是函数ajaxSubmit()

时间:2014-09-25 作者:jharrell

我有一个插件,可以作为标准帖子使用,但不能作为AJAX帖子请求使用。

我在Firebug中得到了一个使用此函数的非函数错误:

类型错误:jQuery(…)。ajaxSubmit不是一个函数

jQuery(this).ajaxSubmit(options);
这一魔法起到了拯救作用:http://codeimpossible.com/2010/01/13/solving-document-ready-is-not-a-function-and-other-problems/

( function($) {

} ) ( jQuery );
这是与我的插件一起排队的js文件-它确实加载在标题中:

jQuery(document).ready(function(){

        var options = { 
            target:         \'#output\',   // target element(s) to be updated with server response 
            beforeSubmit:   beforeSubmit,  // pre-submit callback 
            success:        afterSuccess,  // post-submit callback 
            uploadProgress: OnProgress, //upload progress callback 
            resetForm:      true        // reset the form after successful submit    
        }

    jQuery(\'#nanny_app_upload\').on(\'submit\', function(e) {
                e.preventDefault();

                alert(\'jQuery submit called\');            
                jQuery(this).ajaxSubmit(options);
                alert(\'jQuery post submit\'); 
                // always return false to prevent standard browser submit and page navigation
                alert(\'Got this from the server: \' + response);
                return false;
    });


//function after succesful file upload (when server response)
function afterSuccess(){

    alert(\'jQuery afterSuccess\');
    jQuery(\'#submit-btn\').show(); //show submit button
    jQuery(\'#loading-img\').hide(); //hide loading button
    jQuery(\'#progressbox\').delay( 1000 ).fadeOut(); //hide progress bar
}

//function to check file size before uploading.
function beforeSubmit(){

    alert(\'jQuery beforeSubmit\');
    jQuery(\'#submit-btn\').hide(); //hide submit button
    jQuery(\'#loading-img\').show(); //show loading button
    jQuery("#output").html("");
}

//progress bar function
function OnProgress(event, position, total, percentComplete)
{
    //Progress bar
    alert(\'jQuery OnProgress\');
    jQuery(\'#progressbox\').show();
    jQuery(\'#statustxt\').show();
    jQuery(\'#progressbar\').width(percentComplete + \'%\') //update progressbar percent complete
    jQuery(\'#statustxt\').html(percentComplete + \'%\'); //update status text
    if(percentComplete>50)
        {
            jQuery(\'#statustxt\').css(\'color\',\'#000\'); //change status text to white after 50%
        }
}

});  
以下是从子主题生成的表单:

//Nannie upload form
add_action("action_nannie_upload_form", "do_action_nannie_upload_form");

function do_action_nannie_upload_form()
{   
    $url = plugins_url();
    $plugins_url = $url . "/nannie-app/";
    ?><br>
    An Upload FORM!<br>
    <form action="<?php echo admin_url(\'admin-ajax.php\'); ?>" 
    method="post" enctype="multipart/form-data" id="nannie_app_upload">
    <br>
        <?php wp_nonce_field(\'nannie_app_upload\',\'nannie_upload_ajax_nonce\'); ?>  
        <!-- Add new File -->  
        <span class="btn btn-file">Select file: 
        <input name="FileInput" id="FileInput" type="file" /></span>                
        <button type="submit" class="btn" id="submit-btn">Upload</button>                         
    </form>

    <img src="<?php echo $plugins_url; ?>images/ajax-loader.gif" id="loading-img"
    style="display:none;" alt="Please Wait"/>
    <div id="progressbox" style="display:none;"><div id="progressbar"></div >
    <div id="statustxt">0%</div></div>
    <div id="output"></div>
    <br>
    <br>                    
    <hr/>
<script src="<?php echo get_stylesheet_directory_uri(); ?>/plugins/form/jquery.form.js"></script>
<script src="<?php echo get_stylesheet_directory_uri(); ?>/plugins/uload/ajaxFileUpload.js"></script> 

<?php 
}
下面是表单submit调用的操作。如果我删除对AJAX标题的检查,它会上载文件并将我重定向到空白页面。

add_action("wp_ajax_nopriv_nannie_app_upload", "nannie_app_upload");

function nannie_app_upload(){
    global $wpdb;   

    if(isset($_FILES["FileInput"])){
        log_me("nannie_app_upload: FileInput found");

    if (!isset( $_POST[\'nannie_upload_ajax_nonce\']) || 
       !wp_verify_nonce($_POST[\'nannie_upload_ajax_nonce\'], \'nannie_app_upload\')){
       print \'Sorry, your nonce did not verify.\';
       log_me("nannie_app_upload: nonce did not verify");
       exit;
    }

    if (!isset($_SERVER[\'HTTP_X_REQUESTED_WITH\'])){
        if(isset($_SESSION["naap_app_uid"])){
             $app_uid = $_SESSION["naap_app_uid"];
        }
        log_me(\'nannie_app_upload: AJAX Not Called #\' . $app_uid);
        die();
    }

    //Is file size is less than allowed size.
    if ($_FILES["FileInput"]["size"] > 5242880) {
        log_me(\'nannie_app_upload: File size is too big! #\' . $app_uid);
        die("File size is too big!");
    }       

    $_SESSION["naap_app_uid"] = $app_uid;    
    $UploadDirectory = WP_PLUGIN_DIR."/nannie-app/tmp/" . $app_uid . "/";

        ////////////////////////////////////////////////////
        //http://www.saaraan.com/2012/06/ajax-file-upload-with-php-and-jquery

        if (!@file_exists($UploadDirectory)) {
                //destination folder does not exist
            if(!is_dir($UploadDirectory)) {
                mkdir($UploadDirectory);
                if (!@file_exists($UploadDirectory)) {

                    log_me(\'nannie_app_upload: Upload directory missing for AJAX upload #\' . $app_uid);
                    die("Make sure Upload directory exist!");

                }
            }
        }

        //allowed file type Server side check
        switch(strtolower($_FILES[\'FileInput\'][\'type\']))
        {
                //allowed file types
                case \'image/png\': //png file
                case \'image/gif\': //gif file 
                case \'image/jpeg\': //jpeg file
                case \'application/pdf\': //PDF file
                case \'application/msword\': //ms word file
                case \'application/vnd.ms-excel\': //ms excel file
                case \'application/x-zip-compressed\': //zip file
                case \'text/plain\': //txt file
                case \'text/html\': //html file

                        //File Title will be used as new File name
                        $FileName       = strtolower($_FILES[\'FileInput\'][\'name\']); //uploaded file name
                        $ImageExt       = substr($FileName, strrpos($FileName, \'.\')); //file extension              
                        $NewFileName    = substr($FileName, 0, strrpos($FileName, \'.\') ); //file name before random 

                        $FileType       = $_FILES[\'FileInput\'][\'type\']; //file type
                        $FileSize       = $_FILES[\'FileInput\']["size"]; //file size

                        $RandNumber     = rand(0, 9999999999); //Random number to make each filename unique.
                        $uploaded_date  = date("Y-m-d H:i:s");

                        $NewFileName = preg_replace(array(\'/\\s/\', \'/\\.[\\.]+/\', \'/[^\\w_\\.\\-]/\'), array(\'_\', \'.\', \'\'), strtolower($NewFileName));
                        $NewFileName = $NewFileName.\'_\'.$RandNumber.$ImageExt;

                        //Rename and save uploded file to destination folder.
                        if(move_uploaded_file($_FILES[\'FileInput\']["tmp_name"], $UploadDirectory . $NewFileName )){
                                    //future SQL Insert to record the files uploaded - new table napp_applications_files
                                    log_me(\'nannie_app_upload: Success Upload #\' . $app_uid);
                                    die(\'Success! File Uploaded.\');
                                    break;

                        }else{
                                    log_me(\'nannie_app_upload: Failed Upload #\' . $app_uid);
                                    die(\'error uploading File!\');
                                    break;
                        }            

                        break;
                default:
                        log_me(\'nannie_app_upload: Unsupported Upload #\' . $app_uid);
                        die(\'Unsupported File!\'); //output error enforcing file types
                        break;
        }

    }else{
        log_me(\'nannie_app_upload: Something wrong with upload! Is "upload_max_filesize" set correctly? #\' . $app_uid);
        die(\'Something wrong with upload! Is "upload_max_filesize" set correctly?\');
    }
}

2 个回复
最合适的回答,由SO网友:et-taousy 整理而成

您必须添加jquery.form.min.js 这对我有用,

希望对你有用。

SO网友:fischi

ajaxSubmit 不是jQuery的核心函数。

似乎必须包含jQuery插件(如this), 或者重写函数以使用如下语法,使用jQuery post()

$.post(ajaxurl, data, function(response) {
    // responsefunction
}
或使用jQuery ajax()

$.ajax({
    url: ajaxurl,
    context: data
});
确保你有ajaxurl 在前端定义-WordPress会在后端自动定义它。

顺便说一下,使用post() 使用AJAX,将请求从浏览器异步发送到服务器,然后处理结果。这就是AJAX的含义,即使您的函数没有AJAX这样的名称:)

结束

相关推荐

建议在WP/插件开发中使用Bootstrap还是JQuery-UI?

Bootstrap最近似乎越来越流行,给人一种一致的响应对话框和表单的感觉。现在和将来,使用引导程序或jQuery UI处理对话框、选项卡、表单等通常是最佳实践吗。?据我所见,它们可能都有优势:对于引导:这是一个较新的库,不太可能干扰5个版本之前jQuery ui中包含的、不再受支持的jQuery ui css插件。(不幸的是,它可能与jQuery ui冲突,需要解决办法)。Bootstrap的特性使得Javascript代码对于简单的东西不那么必要。(例如,可以从具有属性目标的按钮打开对话框)。对于jQ