簡體   English   中英

在WordPress中通過AJAX發布上傳文件

[英]Issue uploading file via AJAX in WordPress

意識到圍繞此主題存在一些問題,我今晚大部分時間都在搜索它們,以尋求解決問題的方法。 這是我第一次從事此類任務。

我正在嘗試通過WordPress中的AJAX上傳文件。 我已經在WordPress中設置了AJAX,並且連接正常,直到嘗試傳遞表單數據為止,在該階段我遇到“錯誤請求”錯誤,除此之外沒有其他信息。

WordPress中的AJAX回調函數非常簡單:

add_action( 'wp_ajax_nopriv_calendar_process', 'calendar_process' );
add_action( 'wp_ajax_calendar_process', 'calendar_process' );

function calendar_process() {
    echo "worked";
    die();
}

我的前端表單如下所示:

<form method="post" class="custom-cal-form">
        <input type="file" accept=".ics" name="custom-calendar" id="custom_cal_file" />

        <button class="submit-ajax">Update Calendars</button>
    </form>

我的AJAX調用看起來像這樣:

jQuery( document ).on( 'click', '.submit-ajax', function(e) {

        e.preventDefault();

        var file_data = jQuery('#custom_cal_file').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);
        console.log(form_data);

        jQuery.ajax({

            url : calendarprocess.ajax_url,
            type : 'post',
            processData: false,
            contentType: false,
            data : {
                action : 'calendar_process',
                post_id : 'test',
                calendar : form_data
            },
            success : function( response ) {
                jQuery('.ajax-response').html( response );
            }
        });

    });

我本來是錯誤

只能在FormData實例上調用FormData.append

直到我環顧了一些問題並添加

processData:否,contentType:否,

以我的形式,現在我得到的全部錯誤是:

加載資源失敗:服務器響應狀態為400(錯誤請求)

當然哪個信號表明WordPress不滿意。

真的希望有人可以對此有所了解嗎? 提前致謝。

不熟悉WordPress,但聽起來您的網址不正確。 如果要連接這兩個“變量”? 一起,“。” 在Javascript中無效。 您正在尋找“ +”。 沒有看到它們是從哪里開始的,因此,如果這是特定於WP的,請忽略它,大聲笑。

我要調試的第一件事是對您首先調用的頁面的地址進行硬編碼。 IE瀏覽器“ test / test.php”。 至少可以告訴您它是否是有效地址。

您在enctype="multipart/form-data"錯過了enctype="multipart/form-data" ,因此請嘗試添加它。

<form method="post" class="custom-cal-form" enctype="multipart/form-data">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM