使用$ .ajax

时间:2016-08-29 12:57:30

标签: javascript php jquery mysql ajax

我是$ .ajax的新手并且不知道这么多,我有按下按钮删除文章ID的用户帖子

<button type="button" onclick="submitdata();">Delete</button>

单击此按钮,然后运行$ .ajax进程。

<script>
    var post_id="<?php echo $userIdRow['post_id']; ?>";
    var datastring='post_id='+post_id;
    function submitdata() {
        $.ajax({
            type:"POST",
            url:"delete.php",
            data:datastring,
            cache:false,
            success:function(html) {
                alert(html);
            }
        });
        return false;
    }
</script>

而del​​ete.php是

<?php

// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_GET['post_id']) && is_numeric($_GET['post_id'])) {
// get the 'post_id' variable from the URL
    $post_id = $_GET['post_id'];

// delete record from database
    if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
        $userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
        $userPostsQuery->execute();
        $userPostsQuery->close();
        echo "Deleted success";
    } else {
        echo "ERROR: could not prepare SQL statement.";
    }

}
?>

此代码无效,未删除。请问我该怎么做?

4 个答案:

答案 0 :(得分:4)

您可能不仅希望匹配您在PHP中使用的“GET”,还要将ID添加到按钮

<button class="del" type="button" 
  data-id="<?php echo $userIdRow['post_id']; ?>">Delete</button>

使用符合您的PHP的$ .get或使用$.ajax({ "type":"DELETE"

$(function() {
  $(".del").on("click", function() {
    $.get("delete.php",{"post_id":$(this).data("id")},
       function(html) {
            alert(html);
       }
    );
  });
});

注意:请清除var

Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?

使用带错误处理的ajax DELETE

$(function() {
  $(".del").on("click", function() {
    $.ajax({
      url: "delete.php",
      method: "DELETE", // use "GET" if server does not handle DELETE
      data: { "post_id": $(this).data("id") },
      dataType: "html"
    }).done(function( msg ) {
      $( "#log" ).html( msg );
    }).fail(function( jqXHR, textStatus ) {
      alert( "Request failed: " + textStatus );
    }); 
  });
});

在PHP中你可以做到

if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
  $id = $_REQUEST["post_id"] ....
}

答案 1 :(得分:1)

原因很简单。您应该将您的请求类型更改为GET / DELETE而不是POST。在PHP中,您需要GET请求,但在AJAX中您发送POST请求

变化:

type:"POST",
url:"delete.php",
data:datastring,

type:"DELETE",
url:"delete.php?" + datastring,
PHP中的

if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && !empty($_REQUEST["post_id") {
    $id = $_REQUEST["post_id"];
   // perform delete
}

DELETE实际上是删除对象的唯一有效方法。 POST应该创建一个对象,GET应该检索它。它可能在第一时间令人困惑,但它是REST API中特别使用的好实用程序。如果你想删除对象之间的关系,另一个将是UNLINK。

答案 2 :(得分:1)

因为您正在使用ajax发送帖子请求所以您应该在脚本中使用$ _POST而不是$ _GET 这是怎么回事?

<?php

// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_POST['post_id']) && is_numeric($_POST['post_id'])) {
// get the 'post_id' variable from the URL
    $post_id = $_POST['post_id'];

// delete record from database
    if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
        $userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
        $userPostsQuery->execute();
        $userPostsQuery->close();
        echo "Deleted success";
    } else {
        echo "ERROR: could not prepare SQL statement.";
    }

}
?>
  

用于JS代码

<script>
    var post_id="<?php echo $userIdRow['post_id']; ?>";
    function submitdata() {
        $.ajax({
            type:"POST",
            url:"delete.php",
            data:{"post_id":post_id},
            cache:false,
            success:function(html) {
                alert(html);
            }
        });
        return false;
    }
</script> 

在这里,我认为你可以找到真正的身份证明,并且正在寻找!!

答案 3 :(得分:0)

关注@roberts建议,并且:

你应该有办法处理错误,例如。

到你的ajax代码中添加:

    error:function(e){
     alert(e.statusText)// if you like alerts
     console.log(e.statusText)// If you like console
   }

您还应该检查错误日志。假设你使用apache2和linux 在终端执行此操作:

tail -f /var/log/apache2/error.log 

这为您提供了一种非常精细的代码编写方式。您还可以消除反复试验的问题。