簡體   English   中英

無法弄清楚如何使用$ .ajax將表單數據發布到php

[英]Can't figure out how to POST form data to php with $.ajax

編輯: *更新代碼以反映狀態和當前問題*

我的HTML表單正確接受了input [type = file]。 我知道我追加適當的數據( file.name )到formData 我知道我的腳本archive_upload.php正在被調用,但這是出問題的地方。 $_POST似乎沒有任何作用。 如果我在$len = (int) $_POST['CONTENT_LENGTH'];之后打印$len $len = (int) $_POST['CONTENT_LENGTH']; ,顯示為0。

如何正確檢索發送到腳本的FormData?

這是我的JS:

var formData = new FormData();
var fileSelect = document.getElementById('file');
var uploadButton = document.getElementById('upload');
var form = document.getElementById('file_form');
/*$('#file').change(function() { });*/
form.onsubmit = function(event) {
    event.preventDefault();
    var files = fileSelect.files;

    for (var i=0; i<files.length; i++) {
        var file = files[i];
        if(!file.type.match('image.*')) {
            continue;
        }
        formData.append(i, file.name);
    }
    xhr = new XMLHttpRequest();
    xhr.open('POST', 'archive_upload.php');
    xhr.send(formData);
}

這是我的HTML:

<form id="file_form" action="archive_upload.php" method=POST  enctype=multipart/form-data accept-charset=utf-8>
    <input type="file" id="file" name="photos[]" />
    <button type="submit" id="upload">Upload</button>
</form>

和PHP:

<?php
    $len = (int) $_POST['CONTENT_LENGTH'];
    $files = array();
    for ($i=0; $i < $len; $i++) {
        $f = $_POST[$i]['name'];
        $files.append($f);
    }
    $j = fopen('test.json', 'w');
    fwrite($j, json_encode($files));
    fclose($j);
?>

據我了解,它根本沒有調用ajax頁面,因此請考慮在ajax調用中添加以下代碼段作為選項:

processData: false,
contentType: false,

我相信這篇文章在文件和FormData的類似問題上有經驗

由於您使用HTML表單和Ajax提交表單數據,因此最簡單的方法如下所示:

<script>
$(document).ready(function(){
    $("#upload").click(function(){
        $.ajax({url: "<your url>",
                data: {<put your data here>}
                success: function(result){

                }
                cache: false,
                contentType: false,
                processData: false
    });
    });
});
</script>

HTML形式:

<form id="file_form" action="archive_upload.php" method=POST  enctype=multipart/form-data accept-charset=utf-8>
    <input type="file" id="file" name="photos[]" />
    <button type="button" id="upload">Upload</button>
</form>

暫無
暫無

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

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