【问题标题】:How do we pass data in ajax? [duplicate]我们如何在ajax中传递数据? [复制]
【发布时间】: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 上的链接 :)

标签: php jquery mysql ajax


【解决方案1】:

希望这能传达 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
},

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

删除.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!";
    }

【讨论】:

  • 您的解释非常精彩,但我仍然对如何获取存储在代码echo "&lt;td&gt;&lt;a class='del' href='delete.php' data-ID=$row[0]&gt;Delete&lt;/a&gt;&lt;/td&gt;"; 中的查询字符串中的“id”值感到困惑?
  • 我将更新我的代码以反映这一点。
  • 我删除了准备好的文档,将 onclick 参数添加到按钮,并删除了删除脚本中对 1 的硬编码检查。
  • 非常感谢!你帮了大忙。我对你投了赞成票,但似乎其他人对你的答案投了反对票。我会标记你的答案。再次感谢所有帮助。
  • 我在想,如果使用的方法是get,你打算用什么代替if ($_SERVER['REQUEST_METHOD'] == 'POST')?我认为不使用它会引发variables undefined 错误。
【解决方案2】:

您应该使用所谓的 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);
            }

        })

    })  
})

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

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

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

【讨论】:

  • 我正在使用循环动态显示数据库中的记录。我想获取与单击删除链接对应的记录的“id”值,以便可以将该值发送到服务器并执行删除操作。
【解决方案3】:

只需替换

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

【讨论】:

    猜你喜欢
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 2020-05-27
    相关资源
    最近更新 更多