jQuery HTML5 AJAX 圖片上傳

John Smith發表於2016-07-27
測試時間 2016-07-27
方法 AJAX
前端 jQuery, HTML5
後端 PHP

NO iframe, NO flash  

<!-- 防止頁面亂碼 -->
<meta charset="utf-8">

<!-- 隱藏表單 -->
<form enctype="multipart/form-data" style="display: none;">
<input type="file" id="file" name="file">
</form>

<!-- 上傳按鈕 -->
<button>上傳圖片</button>

<script>
$(function(){ // jquery document ready short form

    // 監聽使用者選中並開啟檔案 file on change
    $('#file').on('change', function () {
        var formData = new FormData($('form')[0]); // FormData is the key
        $.ajax({
            url: 'aaa.php',  // 處理請求的PHP檔案 / 介面
            type: 'POST',
            data: formData, // 傳送的資料
            dataType: 'json', // 返回資料的型別
            success: function (data) {
                $('body').append(data.code);
            },
            error: function () {
                $('body').append('ajax error');
            },
            // cache: false, // not 100% sure if need

            contentType: false, // need
            processData: false // need
        });
    });
    $('button').click(function () {
        $('#file').click();
    });
}); // end of jquery ready
</script>

相關文章