javascript - 使用php进行ajax调用后如何从axios获得正确的响应输出?

标签 javascript php ajax axios

我正在使用 PHP、JS、Axios 和 Ajax 为类似 Instagram 的应用程序制作类似功能。我能够正确启动我想要点击喜欢帖子的特定 a 标签的点击事件处理程序。我的 ajax 调用后得到的响应不允许我检查响应的状态。我从 php 文件传递​​ $response['status']="liked"但通过 ajax 调用获得的数据变量输出不正确。

我首先使用 jquery 实现了该功能,但想使用 axios 来避免 jquery 框架大小导致加载时间过长。

<小时/>

我尝试使用 res.data['status'] 选择状态,但这也不起作用。我似乎得到了一个包含 json 响应的数组。

<小时/>
// this selects the exact like button for the post I want to like using 
// the data attribute id

let btn = document.querySelector("a.like");
btn.addEventListener("click", function(e){
    let postId = this.dataset.id;
    let link = this;
    console.log("test");

    axios.post('ajax/likePost.php',{
        postId : postId

    })
        .then (function (res){
            console.log(res);

            if (res.data == "liked") {
                console.log("we zitten ion de liked");

                let likes = link.nextSibling.innerHTML;
                link.children.src = "images/liked.svg";
                likes++;
                link.nextSibling.innerHTML=likes;
            } else {
                console.log("we zitten ion de niet liked");
                let likes = link.nextSibling.innerHTML;
                link.children.src = "images/like.svg";
                likes--;
                link.nextSibling.innerHTML=likes;
            }
        })
        .catch(function (error) {
            console.log(error);
        });


    e.preventDefault();
});
// this is the php file
<?php

# require bootstrap
require_once("../bootstrap/bootstrap.php");

# check if a session is running with the correct email
if (isset($_SESSION['email'])) {
    //User is logged in, no redirect needed!
} else {
    //User is not logged in, redirect to login.php!
    header("location: login.php");
}

# connect to the database
$conn = Db::getConnection();

# get clicked post info from database
$data = json_decode(file_get_contents("php://input"), true);
//get the postId
$postId = $data['postId'];
var_dump($data);
# create empty response array
$response = [];

# get user info from database (get user id based on the session cookie email)
$sessionEmail = $_SESSION['email'];
$statement = $conn->prepare("SELECT * from user where email = :sessionEmail");
$statement->bindParam(":sessionEmail", $sessionEmail);
$statement->execute();
$currentUser = $statement->fetch(PDO::FETCH_ASSOC);

$userId = $currentUser['id'];

# check if a record exists in the likes table where the current post's id and current user's id are available
$likeStatement = $conn->prepare("SELECT count(*) as count from likes where post_id = :postId AND user_id = :userId");
$likeStatement->bindParam(":postId", $postId);
$likeStatement->bindParam(":userId", $userId);
$likeStatement->execute();
$recordAmount = $likeStatement->fetch(PDO::FETCH_ASSOC);

# if 0 records found => insert new record into the likes table with the current post id, user id en a true liked status
if ($recordAmount['count'] == 0) {
    # first like, so set liked_status to 1
    $liked_status = 1;

    # insert new record
    $insertLikeStatement = $conn->prepare("INSERT INTO likes (post_id, user_id, liked_status) values (:post_id, :user_id, :liked_status)");
    $insertLikeStatement->bindParam(":post_id", $postId);
    $insertLikeStatement->bindParam(":user_id", $userId);
    $insertLikeStatement->bindParam(":liked_status", $liked_status);
    $insertLikeStatement->execute();

    $response['status'] = 'liked';

} else {
    # check if liked status is true or false
    $getLikeStatusStatement = $conn->prepare("SELECT liked_status from likes where post_id = :postId AND user_id = :userId");
    $getLikeStatusStatement->bindParam(":postId", $postId);
    $getLikeStatusStatement->bindParam(":userId", $userId);
    $getLikeStatusStatement->execute();
    $currentLikedStatus = $getLikeStatusStatement->fetch(PDO::FETCH_ASSOC);

    # if post is liked (liked_status 1) change status || if post is not liked, change status
    if ($currentLikedStatus['liked_status'] == 1) {
        $liked_status = 0;
        $response['status'] = 'unliked';
    } else {
        $liked_status = 1;
        $response['status'] = 'liked';
    }

    #update record to contain new liked_status
    $updateStatement = $conn->prepare("update likes set liked_status= :liked_status where post_id = :postId AND user_id = :userId");
    $updateStatement->bindParam(":postId", $postId);
    $updateStatement->bindParam(":userId", $userId);
    $updateStatement->bindParam(":liked_status", $liked_status);
    $updateStatement->execute();
}

header('Content-Type: application/json');
echo json_encode($response);

```

```
// my output in my console when I log the res (response) from the ajax 
// call
array(1) {
  ["postId"]=>
  string(2) "22"
}
{"status":"liked"}
```



I want to get back the status of the like button so I can change the likes number and the image for the button.

最佳答案

您的 PHP 回显的不仅仅是 json 响应。

array(1) {
  ["postId"]=>
  string(2) "22"
}

是由于var_dump($data);。尝试删除它。

关于javascript - 使用php进行ajax调用后如何从axios获得正确的响应输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55854806/

相关文章:

javascript - 它是 firefox 开发者版中的错误吗?

javascript - 如何从元素定位直接子元素

javascript - 我可以使用 $(document).ready(function() { ... });防止全局命名空间污染?

php - jQuery 无法从 href 属性获取文件部分

php - 从 PHP 从 COM 的 DOTNET 类调用 RNGCrypto

使用 Jquery、Django 和 Google App Engine 时,jQuery AJAX 请求被调用两次

javascript - JS/AJAX : Submit form with timer and not a button click or refresh of page

javascript - 在选择选项中更改字符串

php - 如何在 php 的新文本区域中显示 MySQL 中更新的字段

javascript - 使用 Ajax 调用的结果更新 div