0

StackユーザーのDannYoのコメントからいくつかのコードをここに取り込もうとしていますが、彼のコードの私のバージョンは実行されていないようです。エラー関数と「beforesend」関数は毎回返されます。

HTML

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" id="file">
    <input type="email" id="sender" name="sender" required>
    <input type="email" id="receiver" name="receiver" required>
    <input type="text" id="message" name="message">
    <button id="send" class="button">Send it</button>
</form>

JavaScript

$("form").on("submit", function() {

    var formData = new FormData($('form')[0]);

    $.ajax({
        url: 'upload.php',  //server script to process data
        type: 'POST',
        xhr: function() {  // custom xhr

            myXhr = $.ajaxSettings.xhr();

            if (myXhr.upload) { // check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
            }

            return myXhr;

        },

        //Ajax events
        beforeSend: function() { console.log("before send function works"); },
        success: function(e) {
            console.log(e);
        },
        error: function() { console.log("error function works"); },

        // Form data
        data: formData,

        //Options to tell JQuery not to process data or worry about content-type
        cache: false,
        contentType: false,
        processData: false
    });

    return false;

});

PHP

テストの目的で、upload.phpファイルには<?php echo "success"; ?>

Chromeのネットワーク開発者ツールを使用すると、ファイルがどこにも転送されていません。誰かが私のコードに明白な穴を見ますか?ありがとう

4

1 に答える 1

1

エラー関数が呼び出されている場合、その結果の中に答えが含まれている可能性があります。error function works表示してもダメなので、返されるエラーを確認してください。

error: function(xhr, status, error) {
    alert(xhr.responseText);
    // OR
    alert(status + " : " + error);
}

編集:また、アップロードしようとしているファイルの保存を処理する必要があることにも注意してください。phpでファイルをアップロードするためのこのチュートリアルは役に立つかもしれません。

于 2012-07-31T13:46:11.690 に答える