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

时间:2019-04-25 17:34:03

标签: javascript php ajax axios

我正在使用PHP,JS,Axios和Ajax为instagram之类的应用程序提供类似功能。我能够正确启动想要单击要显示为帖子的特定a标签的click事件处理程序。我在执行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.

1 个答案:

答案 0 :(得分:1)

您的PHP不仅回显了json响应,而且回显了

List<string> fileNames = null;
List<string> fileExtensions = null;

private void btn_list_Click(object sender, EventArgs e)
{
    using (FolderBrowserDialog fbd = new FolderBrowserDialog())
    {
        if (fbd.ShowDialog() == DialogResult.OK)
        {
            lbl_path.Text = fbd.SelectedPath;
            fileNames = Directory.GetFiles(fbd.SelectedPath).ToList();
            fileExtensions = fileNames.Select(item => 
                Path.GetExtension(item).Replace(".", "")).Distinct().OrderBy(n => n).ToList();
            listBox_name..DataSource = fileNames.Select(f => Path.GetFileName(f)).ToList();
            listBox_ex.DataSource = fileExtensions;
        }
    }
}

private void btn_CreateFolder_Click(object sender, EventArgs e)
{
    using (FolderBrowserDialog fbd = new FolderBrowserDialog())
    {
        if (fbd.ShowDialog() == DialogResult.OK)
        {
            lbl_pathCreated.Text = fbd.SelectedPath;
            fileExtensions.ForEach(item => 
                Directory.CreateDirectory(Path.Combine(fbd.SelectedPath, item)));
        }
    }
}

归因于array(1) { ["postId"]=> string(2) "22" } 。尝试删除它。