Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 我们如何在ajax中传递数据?_Php_Jquery_Mysql_Ajax - Fatal编程技术网

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

Php 我们如何在ajax中传递数据?,php,jquery,mysql,ajax,Php,Jquery,Mysql,Ajax,我是Ajax新手,对如何在Ajax中传递数据感到困惑。我有一个index.php文件,其中显示了一些数据,它有一个删除记录的链接,现在的问题是,我无法弄清楚如何将所选记录的id值从index.php传输到ajax文件。另外,在delete.php页面中获取了删除记录的代码的值后,我应该如何进行操作。 我的代码如下 index.php delete.php 您应该使用所谓的JSON(我认为是Javascript对象表示法)。这将使您能够更好地对数据进行排序,以便使用,json\u encode 现

我是Ajax新手,对如何在Ajax中传递数据感到困惑。我有一个index.php文件,其中显示了一些数据,它有一个删除记录的链接,现在的问题是,我无法弄清楚如何将所选记录的id值从index.php传输到ajax文件。另外,在delete.php页面中获取了删除记录的代码的值后,我应该如何进行操作。 我的代码如下

index.php delete.php
您应该使用所谓的JSON(我认为是Javascript对象表示法)。这将使您能够更好地对数据进行排序,以便使用,
json\u encode

现在我不太清楚index.php中的
id值是什么意思

但是以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
现在,您可以看到,我们不再只是返回HTML,而是在Javascript中像这样返回
数据
,在php中像这样返回
$result

{
  html : '<div id=" ...',
  debug : ""
}
{
html:“只需替换

echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
在您的PHP中,我建议您使用PDO,它更简单,并且可以防止SQL注入攻击。 PHP:


希望这能传达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>
接下来,我们需要设置脚本

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

@SuperKevin实际上不是Kevin,标题可能匹配,但我的要求完全不同。你不需要在文档中放置.click事件。ready事件。@不要下载,但你的代码容易受到sql注入的攻击检查@abracadver comments:)你解释得很好,但我仍然不清楚该怎么做我应该获取存储在我的代码
echo中的查询字符串中的“id”值吗;
?我将更新我的代码以反映这一点。我删除了document ready,将onclick param添加到按钮,并删除了删除脚本中硬编码的1检查。非常感谢,伙计!你帮了我很大的忙。我对你投了赞成票,但似乎有人对你的答案投了反对票。不过,我会标记你的答案。再次感谢你的帮助。我很好ng,如果使用的方法是
get
,您将使用什么来代替
if($\u SERVER['REQUEST\u METHOD']='POST')
?我认为不使用它将抛出
变量未定义的错误。我使用循环动态显示数据库中的记录。我想获取“id”与单击删除链接对应的记录的值,以便将该值发送到服务器并执行删除操作。
{
  html : '<div id=" ...',
  debug : ""
}
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>";
function deleteRow(recordID)
{
   event.preventDefault();
  $.ajax({
    type: "GET",
     url: "delete.php",
     data:{id: recordID}
    }).done(function( result ) {                    
      alert(result);
  });      
} 
    $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";
}
<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>
data: { /* plugin your data */
    id: 1,
    name: "Bob",
    age: 25
},
<?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!";
    }