第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

使用ajax和php插入mysql的問(wèn)題

使用ajax和php插入mysql的問(wèn)題

PHP
倚天杖 2023-07-08 20:43:53
我想插入mysql的2個(gè)表,一個(gè)表是關(guān)于產(chǎn)品的信息,另一個(gè)表是這些產(chǎn)品的圖像。我有這個(gè)表格<form action="#" method="post" enctype="multipart/form-data" id="upload-multi-images">  <div class="form-group">      <label>Name</label>      <input type="text" name="name" class="form-control" required autocomplete="off">  </div>  <div class="form-group">      <label>Price</label>      <input type="text" name="price" class="form-control" required autocomplete="off">  </div>  <div class="form-group">      <label>Stock</label>      <input type="text" name="stock" class="form-control" required autocomplete="off">  </div>  <div class="row">      <div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" id="add-photo-container">           <div class="add-new-photo first" id="add-photo">               <span><i class="icon-camera"></i></span>           </div>           <input type="file" multiple id="add-new-photo">      </div>  </div>  <div class="button-container">      <button type="submit">Subir imágenes</button>  </div> </form> 我用這個(gè) JS 獲取圖像和信息   $(document).on("submit", "#upload-multi-images", function (e) {    e.preventDefault();   $(document).on("submit", "#upload-multi-images", function (e) {        var namePro = document.getElementsByName('name')[0].value;    var price = document.getElementsByName('price')[0].value;    var stock = document.getElementsByName('stock')[0].value;     formData.append('namePro', namePro);    formData.append('price', price);    formData.append('stock', stock);    e.preventDefault();        //Envio mediante Ajax    $.ajax({        url: "upload.php",        type: "post",        dataType: "json",        data: formData,        cache: false,        contentType: false,        processData: false,        beforeSend: function () {            loading(true, "Adding photo...");        },
查看完整描述

1 回答

?
幕布斯7119047

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊

我沒(méi)有您的所有代碼,但我已經(jīng)確定了您代碼中的問(wèn)題,我將在此處為您添加修復(fù)程序。


首先,如果你使用jquery,最好以統(tǒng)一的格式編寫(xiě)代碼,并在各處使用jquery,而不是在jquery和純JavaScript之間切換。話雖如此,document.getElementsByName您可以輕松地將id屬性添加到 html 元素并使用$('#<id>')jquery 中的方式訪問(wèn)它們,而不是使用。


其次,即使您使用 javascript 來(lái)獲取 html 元素?cái)?shù)據(jù),您所做的也是錯(cuò)誤的。var namePro = document.getElementsByName('name');將選擇整個(gè) html<input>對(duì)象而不是它的值。所以你必須將其更改為:document.getElementsByName("name")[0].value


所以你有兩個(gè)選擇:


1-使用你已有的并將其稍微更改為:


var namePro = document.getElementsByName('name')[0].value;

var price = document.getElementsByName('price')[0].value;

var stock = document.getElementsByName('stock')[0].value; 

2-或者要切換到 jquery,您需要將 id 添加到 html 中的所有這些元素:


<div class="form-group">

    <label>Name</label>

    <input type="text" id="name" name="name" class="form-control" required autocomplete="off">

</div>

<div class="form-group">

    <label>Price</label>

    <input type="text" id="price" name="price" class="form-control" required autocomplete="off">

</div>

<div class="form-group">

    <label>Stock</label>

    <input type="text" id="stock" name="stock" class="form-control" required autocomplete="off">

</div>

然后將 JavaScript 更改為:


formData.append('name', $('#name').val());

formData.append('price', $('#price').val());

formData.append('stock', $('#stock').val());

更新:

在我的機(jī)器上運(yùn)行的示例代碼如下:


HTML:


<form action="#" method="post" enctype="multipart/form-data" id="upload-multi-images">

    <div class="form-group">

        <label>Name</label>

        <input type="text" name="name" class="form-control" required autocomplete="off">

    </div>

    <div class="form-group">

        <label>Price</label>

        <input type="text" name="price" class="form-control" required autocomplete="off">

    </div>

    <div class="form-group">

        <label>Stock</label>

        <input type="text" name="stock" class="form-control" required autocomplete="off">

    </div>

    <div class="row">

        <div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" id="add-photo-container">

            <div class="add-new-photo first" id="add-photo">

                <span><i class="icon-camera"></i></span>

            </div>

            <input type="file" multiple id="add-new-photo">

        </div>

    </div>

    <div class="button-container">

        <button type="submit">Subir imágenes</button>

    </div>

</form>

JS#1:


var formData = new FormData();

$(document).ready(function(){

    $(".modal").on("click", function (e) {

        console.log(e);

        if (($(e.target).hasClass("modal-main") || $(e.target).hasClass("close-modal")) && $("#loading").css("display") == "none") {

            closeModal();

        }

    });


    $(document).on("click", "#add-photo", function(){

        $("#add-new-photo").click();

    });



    $(document).on("change", "#add-new-photo", function () {

        var files = this.files;

        var element;

        var supportedImages = ["image/jpeg", "image/png", "image/gif"];

        var InvalidElementFound = false;


        for (var i = 0; i < files.length; i++) {

            element = files[i];


            if (supportedImages.indexOf(element.type) != -1) {

                var id = getRandomString(7);

                createPreview(element, id);

                formData.append(id, element);

            }

            else {

                InvalidElementFound = true;

            }

        }


        if (InvalidElementFound) {

            showMessage("Invalid Elements Found.");

        }

        else {

            showMessage("All the files were uploaded succesfully.");

        }

    });


    $(document).on("click", "#Images .image-container", function(e){

        var parent = $(this).parent();

        var id = $(parent).attr("id");

        formData.delete(id);

        $(parent).remove();

    });


    $(document).on("submit", "#upload-multi-images", function (e) {

        e.preventDefault();


        var namePro = document.getElementsByName('name')[0].value;

        var price = document.getElementsByName('price')[0].value;

        var stock = document.getElementsByName('stock')[0].value; 


        formData.append('namePro', namePro);

        formData.append('price', price);

        formData.append('stock', stock);


        //Envio mediante Ajax

        $.ajax({

            url: "upload.php",

            type: "post",

            dataType: "json",

            data: formData,

            cache: false,

            contentType: false,

            processData: false,

            beforeSend: function () {

                loading(true, "Adding photo...");

            },

            success: function (res) {

                console.log('success');

                console.log(res);

                loading(false);

                if (res.status == "true") {

                    createImages(res.all_ids);

                    $("#Images form .row > div:not(#add-photo-container)").remove();

                    formData = new FormData();

                } else {

                    alert(res.error);

                }

            },

            error: function (e) {

                console.log('error');

                console.log(e.responseText);

            }

        });

    });


    $(document).on("click", "#MyImages .image-container", function (e) {

        var parent = $(this).parent();

        var id = $(parent).attr("data-id");

        var data = {

            id : id

        }


        $.post("delete.php", data, function(res) {

            if (res == "true") {

                showMessage("?Images successfully removed!");

                $(parent).remove();

            }

            else {

                showMessage("Sorry, there was an error uploading the images.");

            }

        });

    });

});

JS#2:


function getRandomString(length) {

    var text = "";

    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";


    for (var i = 0; i < length; i++) {

        text += possible.charAt(Math.floor(Math.random() * possible.length));

    }


    return text;

}


function createPreview(file, id) {

    var imgCodified = URL.createObjectURL(file);

    var img = $('<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" id="'+ id + '"><div class="image-container"> <figure> <img src="' + imgCodified + '" alt="Foto del usuario"> <figcaption> <i class="icon-cross"></i></figcaption> </figure> </div></div>');

    $(img).insertBefore("#add-photo-container");

}


function createImages(all_ids) {

    for (const key in all_ids) {

        var image = all_ids[key];


        var img = $('<div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" data-id="' + image.id + '"><div class="image-container"> <figure> <img src="images/' + image.name + '" alt="Foto del usuario"> <figcaption> <i class="icon-cross"></i> </figcaption> </figure> </div></div>');

        $("#my-images").append(img);

    }    

}


function showModal(card) {

    $("#" + card).show();

    $(".modal").addClass("show");

}


function closeModal() {

    $(".modal").removeClass("show");

    setTimeout(function () {

        $(".modal .modal-card").hide();

    }, 300);

}


function loading(status, tag) {

    if (status) {

        $("#loading .tag").text(tag);

        showModal("loading");

    }

    else {

        closeModal();

    }

}


function showMessage(message) {

    $("#Message .tag").text(message);

    showModal("Message");

}

PHP:(上傳.php)


$arr_ajax = array();


$arr_ajax['namePro'] = $_REQUEST['namePro'];

$arr_ajax['price'] = $_REQUEST['price'];

$arr_ajax['stock'] = $_REQUEST['stock'];


if (isset($_FILES) && !empty($_FILES)) {

    $files = array_filter($_FILES, function($item) {

        return $item["name"][0] != "";

    });

    

    $iCnt = 0;

    foreach ($files as $file) {

        $arr_ajax['Filename'.$iCnt] = $file["name"];

        $iCnt++;

    }

}


echo json_encode($arr_ajax);

使用此代碼,當(dāng)我單擊“提交”按鈕時(shí),我會(huì)在瀏覽器控制臺(tái)中收到以下響應(yīng):


index.html:79 success

index.html:80 {namePro: "Test Product", price: "100.00", stock: "15", Filename0: "faces1.jpg"}



查看完整回答
反對(duì) 回復(fù) 2023-07-08
  • 1 回答
  • 0 關(guān)注
  • 140 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)