使用ajax和php插入mysql的问题

我想插入mysql的2个表,一个表是关于产品的信息,另一个表是这些产品的图像。我有这个表格


<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 获取图像和信息


   $(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...");

        },


倚天杖
浏览 114回答 1
1回答

幕布斯7119047

我没有您的所有代码,但我已经确定了您代码中的问题,我将在此处为您添加修复程序。首先,如果你使用jquery,最好以统一的格式编写代码,并在各处使用jquery,而不是在jquery和纯JavaScript之间切换。话虽如此,document.getElementsByName您可以轻松地将id属性添加到 html 元素并使用$('#<id>')jquery 中的方式访问它们,而不是使用。其次,即使您使用 javascript 来获取 html 元素数据,您所做的也是错误的。var namePro = document.getElementsByName('name');将选择整个 html<input>对象而不是它的值。所以你必须将其更改为:document.getElementsByName("name")[0].value所以你有两个选择:1-使用你已有的并将其稍微更改为:var namePro = document.getElementsByName('name')[0].value;var price = document.getElementsByName('price')[0].value;var stock = document.getElementsByName('stock')[0].value;&nbsp;2-或者要切换到 jquery,您需要将 id 添加到 html 中的所有这些元素:<div class="form-group">&nbsp; &nbsp; <label>Name</label>&nbsp; &nbsp; <input type="text" id="name" name="name" class="form-control" required autocomplete="off"></div><div class="form-group">&nbsp; &nbsp; <label>Price</label>&nbsp; &nbsp; <input type="text" id="price" name="price" class="form-control" required autocomplete="off"></div><div class="form-group">&nbsp; &nbsp; <label>Stock</label>&nbsp; &nbsp; <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());更新:在我的机器上运行的示例代码如下:HTML:<form action="#" method="post" enctype="multipart/form-data" id="upload-multi-images">&nbsp; &nbsp; <div class="form-group">&nbsp; &nbsp; &nbsp; &nbsp; <label>Name</label>&nbsp; &nbsp; &nbsp; &nbsp; <input type="text" name="name" class="form-control" required autocomplete="off">&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="form-group">&nbsp; &nbsp; &nbsp; &nbsp; <label>Price</label>&nbsp; &nbsp; &nbsp; &nbsp; <input type="text" name="price" class="form-control" required autocomplete="off">&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="form-group">&nbsp; &nbsp; &nbsp; &nbsp; <label>Stock</label>&nbsp; &nbsp; &nbsp; &nbsp; <input type="text" name="stock" class="form-control" required autocomplete="off">&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="row">&nbsp; &nbsp; &nbsp; &nbsp; <div class="col-xl-2 col-lg-2 col-md-3 col-sm-4 col-xs-12" id="add-photo-container">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div class="add-new-photo first" id="add-photo">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span><i class="icon-camera"></i></span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="file" multiple id="add-new-photo">&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; &nbsp; <div class="button-container">&nbsp; &nbsp; &nbsp; &nbsp; <button type="submit">Subir imágenes</button>&nbsp; &nbsp; </div></form>JS#1:var formData = new FormData();$(document).ready(function(){&nbsp; &nbsp; $(".modal").on("click", function (e) {&nbsp; &nbsp; &nbsp; &nbsp; console.log(e);&nbsp; &nbsp; &nbsp; &nbsp; if (($(e.target).hasClass("modal-main") || $(e.target).hasClass("close-modal")) && $("#loading").css("display") == "none") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; closeModal();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; $(document).on("click", "#add-photo", function(){&nbsp; &nbsp; &nbsp; &nbsp; $("#add-new-photo").click();&nbsp; &nbsp; });&nbsp; &nbsp; $(document).on("change", "#add-new-photo", function () {&nbsp; &nbsp; &nbsp; &nbsp; var files = this.files;&nbsp; &nbsp; &nbsp; &nbsp; var element;&nbsp; &nbsp; &nbsp; &nbsp; var supportedImages = ["image/jpeg", "image/png", "image/gif"];&nbsp; &nbsp; &nbsp; &nbsp; var InvalidElementFound = false;&nbsp; &nbsp; &nbsp; &nbsp; for (var i = 0; i < files.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; element = files[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (supportedImages.indexOf(element.type) != -1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var id = getRandomString(7);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; createPreview(element, id);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; formData.append(id, element);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; InvalidElementFound = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (InvalidElementFound) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; showMessage("Invalid Elements Found.");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; showMessage("All the files were uploaded succesfully.");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; $(document).on("click", "#Images .image-container", function(e){&nbsp; &nbsp; &nbsp; &nbsp; var parent = $(this).parent();&nbsp; &nbsp; &nbsp; &nbsp; var id = $(parent).attr("id");&nbsp; &nbsp; &nbsp; &nbsp; formData.delete(id);&nbsp; &nbsp; &nbsp; &nbsp; $(parent).remove();&nbsp; &nbsp; });&nbsp; &nbsp; $(document).on("submit", "#upload-multi-images", function (e) {&nbsp; &nbsp; &nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; &nbsp; &nbsp; var namePro = document.getElementsByName('name')[0].value;&nbsp; &nbsp; &nbsp; &nbsp; var price = document.getElementsByName('price')[0].value;&nbsp; &nbsp; &nbsp; &nbsp; var stock = document.getElementsByName('stock')[0].value;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; formData.append('namePro', namePro);&nbsp; &nbsp; &nbsp; &nbsp; formData.append('price', price);&nbsp; &nbsp; &nbsp; &nbsp; formData.append('stock', stock);&nbsp; &nbsp; &nbsp; &nbsp; //Envio mediante Ajax&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: "upload.php",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: "post",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: formData,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cache: false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; contentType: false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; processData: false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; beforeSend: function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; loading(true, "Adding photo...");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function (res) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('success');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(res);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; loading(false);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (res.status == "true") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; createImages(res.all_ids);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#Images form .row > div:not(#add-photo-container)").remove();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; formData = new FormData();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(res.error);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; error: function (e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('error');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(e.responseText);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });&nbsp; &nbsp; $(document).on("click", "#MyImages .image-container", function (e) {&nbsp; &nbsp; &nbsp; &nbsp; var parent = $(this).parent();&nbsp; &nbsp; &nbsp; &nbsp; var id = $(parent).attr("data-id");&nbsp; &nbsp; &nbsp; &nbsp; var data = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id : id&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $.post("delete.php", data, function(res) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (res == "true") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; showMessage("¡Images successfully removed!");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(parent).remove();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; showMessage("Sorry, there was an error uploading the images.");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });});JS#2:function getRandomString(length) {&nbsp; &nbsp; var text = "";&nbsp; &nbsp; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";&nbsp; &nbsp; for (var i = 0; i < length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; text += possible.charAt(Math.floor(Math.random() * possible.length));&nbsp; &nbsp; }&nbsp; &nbsp; return text;}function createPreview(file, id) {&nbsp; &nbsp; var imgCodified = URL.createObjectURL(file);&nbsp; &nbsp; 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>');&nbsp; &nbsp; $(img).insertBefore("#add-photo-container");}function createImages(all_ids) {&nbsp; &nbsp; for (const key in all_ids) {&nbsp; &nbsp; &nbsp; &nbsp; var image = all_ids[key];&nbsp; &nbsp; &nbsp; &nbsp; 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>');&nbsp; &nbsp; &nbsp; &nbsp; $("#my-images").append(img);&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;}function showModal(card) {&nbsp; &nbsp; $("#" + card).show();&nbsp; &nbsp; $(".modal").addClass("show");}function closeModal() {&nbsp; &nbsp; $(".modal").removeClass("show");&nbsp; &nbsp; setTimeout(function () {&nbsp; &nbsp; &nbsp; &nbsp; $(".modal .modal-card").hide();&nbsp; &nbsp; }, 300);}function loading(status, tag) {&nbsp; &nbsp; if (status) {&nbsp; &nbsp; &nbsp; &nbsp; $("#loading .tag").text(tag);&nbsp; &nbsp; &nbsp; &nbsp; showModal("loading");&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; closeModal();&nbsp; &nbsp; }}function showMessage(message) {&nbsp; &nbsp; $("#Message .tag").text(message);&nbsp; &nbsp; 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)) {&nbsp; &nbsp; $files = array_filter($_FILES, function($item) {&nbsp; &nbsp; &nbsp; &nbsp; return $item["name"][0] != "";&nbsp; &nbsp; });&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; $iCnt = 0;&nbsp; &nbsp; foreach ($files as $file) {&nbsp; &nbsp; &nbsp; &nbsp; $arr_ajax['Filename'.$iCnt] = $file["name"];&nbsp; &nbsp; &nbsp; &nbsp; $iCnt++;&nbsp; &nbsp; }}echo json_encode($arr_ajax);使用此代码,当我单击“提交”按钮时,我会在浏览器控制台中收到以下响应:index.html:79 successindex.html:80 {namePro: "Test Product", price: "100.00", stock: "15", Filename0: "faces1.jpg"}
打开App,查看更多内容
随时随地看视频慕课网APP