我有一个关于使用 ajax 的问题。我想删除屏幕上的某些内容(要清楚,一些文章(我正在使用以下代码在屏幕上生成内容(文章(:
while($test = $allArticles->fetch_assoc())
{
echo "<div class='metfoto'>";
echo "<h1 name='tt' class='titelopmaak'>".$test['titel'] . "<br /></h1>";
echo "<p class='artikelopmaak'>" . $test['article'] . "</p>";
echo "<form method='post' action=''>";
echo "<input type='submit' class='delete' name='verwijder' value='verwijder'>";
echo "</form>";
//echo "<h1>".$test['id']."</h1>";
echo "</div>";
}
这一切都在没有 ajax 的情况下运行良好。 但我想在没有页面刷新的情况下做到这一点(带按钮的删除(。例如,当我检查$test['id']的内容时,我会收到一个数字。我对以下代码的问题是,当我想将标题放入 ajax 的 variabel (var titel( 中时,它会从我的页面加载所有标题。
<script type="text/javascript">
$(document).ready(function(){
$(".delete").click(function(){
var titel = $(".titelopmaak").text();
var artikel = $(".artikelopmaak").text();
$.ajax({
type: "POST",
url: "assets/ajax/deleteArticle.php",
data: { titelA:titel },
}).done(function( msg ) {
if(msg.status != "error")
{
if(msg.status == "success")
{
$(".titelopmaak").fadeOut();
}
else
{
}
}
});
return false;
})
});
</script>
编辑
我希望我现在以更好的方式解释了我的问题
你的问题就在这里
var titel = $(".titelopmaak").text();
您可以使用类 .titelopmaak
获取元素的所有值,但您只需要一个。
这是正确的,我们上树,然后找到项目。
var titel = $(this).closest('.metfoto').find('.titelopmaak').text();
但是,控制元素的标题是非常糟糕的做法,使用 id 而不是。
<script>
$(document).ready( function(){
$('.delete').submit( function() {
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
type: $(this).attr('method'),
success: function(data, status, jqXHR) {
$(".titelopmaak").fadeOut();
},
error: function(jqXHR, textStatus, errorThrown) {
}
);
});
});
</script>
<? while($test = $allArticles->fetch_assoc()) { ?>
<form method="POST" action="" class="delete">
<input type="hidden" value="<?=$test['id']?>" name="delete">
<input type="submit" value='verwijder'>
</form>
<? } ?>
你可以
这样尝试。
您必须为每个 html 元素指定单独的 id
while($test = $allArticles->fetch_assoc())
{
$cid = $test['id'];
echo "<div id='div$cid' class='metfoto'>";
echo "<h1 name='tt' id='h1$cid' class='titelopmaak'>".$test['titel'] . "<br /></h1>";
echo "<p id='para$cid' class='artikelopmaak'>" . $test['article'] . "</p>";
echo "<input type='submit' class='delete' name='verwijder' id='verwijder$cid' onclick='deleteValue($cid);' value='verwijder'>";
echo "</div>";
}
JavaScript函数
通过 id 引用 h1 和div。
<script type="text/javascript">
function deleteValue(cid)
{
var titel = $("#h1"+cid).text();
var artikel = $("#para"+cid).text();
$.ajax({
type: "POST",
url: "assets/ajax/deleteArticle.php",
data: { titelA:titel },
}).done(function( msg ) {
if(msg.status != "error")
{
if(msg.status == "success")
{
$("#h1"+cid).fadeOut();
}
else
{
}
}
});
return false;
})
}
</script>
删除文章.php
include "connection.php";
$title = $_POST['titelA'];
$ok = mysql_query("delete from yourtable where title='$title');
echo "your msg here";