繁体   English   中英

如何用ajax上载没有格式的输入文件?

[英]How to upload an input file with ajax without form?

我有一个动态表,该表通过ajax将所有输入文本发送到我的数据库中。

到目前为止,这是我的代码。

<script language="javascript" type="text/javascript">

var i = 2; //This varaible serves to always be "positionned" on the last row

function test(select) {
       //Here I'm cheking that somes inputs are not empty
            /*if (select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[0].firstChild.value == "") {
                alert("Veuillez rentrer un nom d'ingrédient");
            }
            else if (select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[1].firstChild.value == "") {
                alert("Veuillez rentrer un code pour l'ingrédient");
            }*/

            //Now I'm selecting all values from input in my table and post them to another page with ajax
            var id_produit = select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[8].firstChild.value; //I need this variable to create rows
            var data = 'nom_ingredient='+select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[0].firstChild.value
            + '&code_ingredient='+select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[1].firstChild.value
            + '&conditionnement_ingredient='+select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[2].firstChild.value
            + '&fiche_technique_ingredient='+select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[3].firstChild.files[0] // <<<<< THIS IS MY INPUT FILE !
            + '&commentaire_ingredient='+select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[7].firstChild.value
            + '&id_produit='+select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[8].firstChild.value;
            $.ajax({
                url: "ajout-ingredient.php",
                type: "POST",
                data: data,
                success: function()
                {
                    alert(data);
                    addligne(select, id_produit); //The function that creates rows
                    i++;

                },
                error: function (xhrReq, textstatus, errorThrown) {
                            alert(xhrReq.status);
                            alert(errorThrown);
                        }
            });
            return false;
            /*}*/
    }

function addligne(select, id_produit) { //The function to create rows
<?php
$usine = $GLOBALS['usine']; //By doing this, I'm starting to create a <select>
?>
var usine = <?php echo json_encode($usine) ?>;
    var element2 = document.createElement("select");

    for (var j = 0; j < usine.length; j++) {
    var option = document.createElement("option");
    option.value = usine[j].id_usine;
    option.text = usine[j].nom_usine;
    element2.appendChild(option);
    }

    var table = select.parentNode.parentNode.parentNode.parentNode.tBodies[1]; //Selecting the table where I want to create rows
    var row = table.insertRow(-1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    var cell5 = row.insertCell(4);
    var cell6 = row.insertCell(5);
    var cell7 = row.insertCell(6);
    var cell8 = row.insertCell(7);
    var cell9 = row.insertCell(8);


    cell1.innerHTML = '<input type="text" name="nom_ingredient" value="" placeholder="Ingredient '+i+'"/>';
    cell2.innerHTML = '<input type="text" name="code_ingredient" value=""/>';
    cell3.innerHTML = '<input type="text" name="conditionnement_ingredient" value=""/>';
    cell4.innerHTML = '<input type="file" name="fiche_technique_ingredient"/>';
    cell5.innerHTML = '<input type="file" name="certificat_ingredient"/>';
    cell6.innerHTML = '<input type="file" name="photo_ingredient"/>';
    cell7.appendChild(element2);
    cell8.innerHTML = '<input type="text" name="commentaire_ingredient"/></td>';
    cell9.innerHTML = '<input type="hidden" name="id_produit" value="'+id_produit +'" />';
}


</script>

这是我的“ ajout-ingredient.php”页面:

<?php
require_once (__DIR__.'/../base/singleton.php');
if($_POST)
{
$nom_ingredient=$_POST['nom_ingredient'];
$code_ingredient=$_POST['code_ingredient'];
$conditionnement_ingredient=$_POST['conditionnement_ingredient'];
$commentaire_ingredient=$_POST['commentaire_ingredient'];
$id_produit=$_POST['id_produit'];


    try {
        $PDO = myPdo::getInstance();
    }
    catch (PDOException $e) {
        die('Une erreur interne est survenue');
    }
    $req = $PDO->query('INSERT INTO ingredient (nom_ingredient, code_ingredient, conditionnement_ingredient, commentaire_ingredient, id_admin) 
                        VALUES ("'.$nom_ingredient.'", "'.$code_ingredient.'", "'.$conditionnement_ingredient.'", "'.$commentaire_ingredient.'", "1")');
    $last = $PDO->lastInsertId();
    $req2 = $PDO->query('INSERT INTO composer_produit_ingredient (id_ingredient, id_produit) VALUES ("'.$last.'", "'.$id_produit.'")');


    //Part to upload a file
    //This is where I'm stuck..

    $select_nom = $PDO->query('SELECT nom_societe_client from client as c 
                        JOIN demande as d on c.id_client = d.id_client
                        JOIN composer_demande_produit as c_d_p on d.id_demande = c_d_p.id_demande
                        JOIN composer_produit_ingredient as c_d_i on c_d_p.id_produit = c_d_i.id_produit
                        Where id_ingredient = "'.$last.'" ');
    $select_nom = $select_nom->fetchColumn();
    $select_nom = str_replace(' ', '', $select_nom);
    $dossier = $select_nom;
    $chemin_base = "../upload/";
    $chemin_final = $chemin_base . $dossier;
            if (is_dir($chemin_final)) {
            }
            else{
                mkdir($chemin_final);
            }
            $_FILES['name'] = str_replace(' ', '', $_FILES['name']);
            $test = $chemin_final . "/";
            $fichier = $test.$_FILES['name'];
            if(is_uploaded_file($_FILES['tmp_name'])) {
                $chemin = $chemin_final."/".$_FILES['name'];
                $today = date("Y-m-d H:i:s");
                $req = $PDO->prepare('INSERT INTO document (chemin_doc, type_document, date_upload, id_ingredient) 
                        VALUES ("'.$chemin.'", "fiche_technique_ingredient", "'.$today.'", "'.$last.'")');
                $req ->execute();
                if(!move_uploaded_file($_FILES['tmp_name'], $fichier)) {
                    echo "Problème : Impossible de déplacer le fichier dans son répertoire de destination.";
                    exit;
                }
            }
}

else {
}

?>

因此,每个值都正确地输入了我的数据库,但是我仍然无法上传文件。.我认为这是因为我无法将输入文件从脚本传递到ajout-ingredient.php页面。上传文件是可行的,因为我以前使用过她:)

提前致谢 !

您可以轻松地做到这一点而无需提交表单,但是首先应该将要传递的所有输入包装在form元素中

<form id="your_form" method="post" enctype="multipart/form-data">...</form>

然后,您可以使用FormData使用AJAX将所有输入传递到您的php脚本(包括文件)

test(select) {

....
var your_form = $('#your_form')[0];
var formData = new FormData(your_form);
.....
$.ajax({
            url: "ajout-ingredient.php",
            type: "POST",
            data: formData,
            contentType: false,
            processData: false,
.....

如果由于某种原因您不想在html中包含form元素,则可以只创建formData对象,然后将想要的数据一一追加

var formData = new FormData();

var code_ingredient=select.parentNode.parentNode.parentNode.parentNode.rows[i].cells[1].firstChild.value;

formData.append("code_ingredient", code_ingredient);                   //to append your values
....
formData.append('certificat_ingredient', $('input[name="certificat_ingredient"]')[0].files[0]);  //to append your files

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM