【发布时间】:2018-02-16 17:46:19
【问题描述】:
我是 Ajax 的新手,我对我们如何在 Ajax 中传递数据感到困惑。我有一个显示一些数据的 index.php 文件,它有一个删除记录的链接,现在的问题是,我无法弄清楚如何将 id 值从所选记录的 index.php 传输到 ajax 文件.另外,一旦我在 delete.php 页面中获取了值,我应该如何处理删除记录的代码。 我编码如下。
index.php
<div id="delMsg"></div>
<?php
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
echo "<table>";
while($row=mysqli_fetch_array($data))
{
echo "<tr>";
for($i=0;$i<$col;$i++)
{
echo "<td>".$row[$i]."</td>";
}
echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
echo"</tr>";
}
echo "</table>";
?>
ajax-file.js
$(document).ready(function(){
$(".del").click(function(event){
event.preventDefault();
$.ajax({
url:"delete.php",
method:"get",
data:{id:'ID'},
dataType:"html",
success:function(str){
$('#delMsg').html(str);
}
})
})
})
删除.php
<?php
$id=$_GET['id'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"delete from member where id='$id'");
if($data)
{
echo "success";
}
else
{
echo "error";
}
?>
【问题讨论】:
-
@SuperKevin 实际上不是凯文,标题可能匹配,但我问的是完全不同的事情。
-
您不需要在 document.ready 事件中放置 .click 事件。
-
@Don'tDownvoteMe 不是,但您的代码容易受到 sql 注入的影响
-
查看@AbraCadaver cmets 上的链接 :)