我正在使用AJAX将隐藏的输入值传递给另一页并显示在其中, 但价值没有传递。我是PHP,jQuery和AJAX的新手。有人可以帮我吗?
index.php:
<?php
foreach($imgs as $keys => $vals)
{
echo '<img class="myimg1" id="myimg" src="' . "images/$vals" . '" width="20%" height="20%"/>';
echo '<input type="hidden" value="'.$vals.'" name="delete_file" id="delete_file" />';
echo '<input type="button" value="Delete image" onclick="delete_image()"/>';
}
?>
js
function delete_image() {
var status = confirm("Are you sure you want to delete ?");
if (status == true) {
var file = $("#delete_file").val();
$.ajax({
type: "POST",
url: "action.php",
data: { file: file },
success(html) {
alert('Deleted');
}
});
}
}
action.php
<?php
$num = $_POST["file"];
echo $num;
?>
答案 0 :(得分:0)
我希望以下解决方案能够为您提供帮助。
我将输入类型按钮中的onclick函数和功能修改为delete_name(ele)
var file = ele;
echo '<img class="myimg1" id="myimg" src="' . "images/$vals" . '" width="20%" height="20%"/>';
echo '<input type="hidden" value="'.$vals.'" name="delete_file" id="delete_file" />';
echo '<input type="button" value="Delete image" onclick="delete_image('.$vals.')"/>';
function delete_image(ele) {
var status = confirm("Are you sure you want to delete ?");
if (status == true) {
var file = ele;
$.ajax({
type: "POST",
url: "action.php",
data: { file: file },
success(html) {
alert('Deleted');
}
});
}
}
答案 1 :(得分:-1)
您正在循环播放图像,所有这些图像都具有相同的名称和ID。不好我将对其进行更改,以便他们都获得不同的名称和ID。
<?php
$counter = 0;
foreach($imgs as $keys => $vals)
{
echo '<img class="myimg1" id="myimg" src="' . "images/$vals" . '" width="20%" height="20%"/>';
echo '<input type="hidden" value="'.$vals.'" name="delete_file[' . $counter . ']" id="delete_file_' . $counter . '" />';
echo '<input type="button" value="Delete image" onclick="delete_image()"/>';
$counter++;
}
?>
您还可以将图像放入表单中,并使用jQuery序列化以通过Ajax发送。
还更改以下内容的成功部分以查看PHP错误:
function delete_image() {
var status = confirm("Are you sure you want to delete ?");
if (status == true) {
var file = $("#delete_file").val();
$.ajax({
type: "POST",
url: "action.php",
data: { file: file },
success: function(data, textStatus, jqXHR) {
// use console.log to find PHP errors in the console of the browser
console.log(data);
// you can alert data or use is to check for errors of whatever you want
if (data == 'success') { alert(data); }
}
});
}
}