1 回答
TA贡献1794条经验 获得超8个赞
我没有您的所有代码,但我已经确定了您代码中的问题,我将在此处为您添加修复程序。
首先,如果你使用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;
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());
更新:
在我的机器上运行的示例代码如下:
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);
使用此代码,当我单击“提交”按钮时,我会在浏览器控制台中收到以下响应:
index.html:79 success
index.html:80 {namePro: "Test Product", price: "100.00", stock: "15", Filename0: "faces1.jpg"}
- 1 回答
- 0 关注
- 113 浏览
添加回答
举报