我们如何在ajax中传递数据?

时间:2018-02-16 17:46:19

标签: php jquery mysql ajax

我是Ajax的新手,我对如何在Ajax中传递数据感到困惑。我有一个index.php文件显示一些数据,它有一个删除记录的链接,现在问题是,我无法弄清楚如何将所选记录的index.php中的id值传递给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);
            }

        })

    })  
})

delete.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";   
}

?>

3 个答案:

答案 0 :(得分:0)

你应该使用所谓的JSON(Javascript Object Notation,我认为)。这样您就可以更好地订购数据,以便使用json_encode

现在我不确定这个id value from index.php

的含义

但是拿你的index.php文件,我会像这样改变它

//make sure the is no space here
<?php
//start output buffering
ob_start();
$html = ['<div id="delMsg"></div>'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
$html[] = "<table>";
while($row=mysqli_fetch_array($data))
{
    $html[] = "<tr>";
    for($i=0;$i<$col;$i++)
    {
        $html[] = "<td>".$row[$i]."</td>";

    }
    $html[] = "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
    $html[] = "</tr>";
}
$html[] = "</table>";

$result = [
    'html' => implode("\n", $html),
    'debug' => ob_get_clean()
];

header("Content-type:application/json");
echo json_encode($result);

//?> ending tags are undesirable

您的JavaScript部分也会改变

$(document).ready(function(){
    $(".del").click(function(event){
    event.preventDefault();
    $.ajax({
        url:"delete.php",
        method:"get",
        data:{id:'ID'},
        dataType:"html",
        success:function(data){
            $('#delMsg').html(data.html);
            }

        })

    })  
})

您现在可以看到,我们将返回它,而不仅仅是返回HTML,我们将在Javascript中将其返回data并在PHP中$result

{
  html : '<div id=" ...',
  debug : ""
}

我添加了ob_startob_get_clean这可能会有所帮助,因为您不能在输出JSON时回显内容,因此这将捕获任何echo或print_r类型的内容并将其放入debug回报中的项目。

答案 1 :(得分:0)

希望这传达了AJAX调用如何工作的想法。

我们要做的第一件事就是设置我们的触发器,在你的情况下是一个带有onclick事件的按钮。

<script
  src="http://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>

<!-- <button id="delete">Delete Something</button> -->
<button id="delete" onclick="onClickHandler(5)">Delete Something</button>

<p id="message">AJAX</p>

<script>
/* Notice I removed the document ready */
function onClickHandler(id)
{
    event.preventDefault();
    $.ajax(
    {
        url:"delete.php",
        method:"POST", /* In the real world you want to use a delete here */
        data: { /* plugin your data */
            id: id,
            name: "Bob",
            age: 25
        },
        dataType:"html",
        success: function(success)  {
            // Handle the success message here!

            if (success) {
                $('#message').text("Your message was received!");
            }
        },
        error: function(error) {
            // Handle your errors here
            $('#message').text("Something went wrong!");
        }
    });
};
</script>

注意我的数据是如何在数据对象中准备的。我让你知道如何获取数据并将其设置在正确的字段中。您可以:$('#someId').value();或通过函数传递它。如果这是一个混乱的来源,我可以澄清。

data: { /* plugin your data */
    id: 1,
    name: "Bob",
    age: 25
},

接下来,我们需要设置我们的脚本。

<强> delete.php

<?php

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        // Obviously validate the data.
        // But this is how you access it.
        // $_POST is a global array, so you can access it like so:
        $id = $_POST['id'];
        $name = $_POST['name'];
        $age = $_POST['age'];

        // Do your server side stuff...
        $sql = "DELETE FROM member
                WHERE id = '{$id}' AND name = '{$name}' AND age = '{$age}'";

        // Do your SQL (delete) here
        // $con = mysqli_connect("localhost","root","","ajaxtest");
        // Use prepared statements http://bobby-tables.com/php
        // $data = mysqli_query($con,"delete from member where id='$id'");

        // if ($data) { // Your condition

        // This is where you would check if the query passed
        // and send back the appropriate message.
        if ($id) {
            echo json_encode($id);
        }
        else {
            echo http_response_code(500);
        }
    }
    else {
        echo "You don't belong here!";
    }

答案 2 :(得分:-1)

只需替换

echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";

echo "<td><a onclick="deleteRow($row[0])">Delete</a></td>";

的Javascript

function deleteRow(recordID)
{
   event.preventDefault();
  $.ajax({
    type: "GET",
     url: "delete.php",
     data:{id: recordID}
    }).done(function( result ) {                    
      alert(result);
  });      
} 

在您的PHP中,我建议您使用PDO,这样可以更轻松地防止SQL注入攻击。 PHP:

    $db = new PDO('mysql:host=localhost;dbname=yourDB','root','');
$query = $db->prepare("Delete From yourTableName Where ID=:ID");
$id=$_GET['id'];
$query->bindParam('ID', $id);
$query->execute();

if ($query->rowCount()) {
    echo "success";
}
else
{
    echo "fails";
}