通过Ajax将Localstorage json数据传递到php sql查询(稍后阅读功能)

时间:2018-11-17 19:54:09

标签: javascript php json ajax

我正在尝试为我的博客网站构建一个“稍后阅读”(收藏夹)功能。 我想使用localstorage将我的博客帖子(通常是很短的帖子)的postID保存为json,然后通过简单的AJAX(无jquery)POST和php GET,在一页上显示保存的帖子

我通过以下方式将postID列表写到localstorage save.php:

<html>
<head>
<style>
.list li {
  cursor: pointer;
}
.list li:hover:after,
.list li.fav:after {
  content: ' \2605';
  color: rgb(255, 203, 0);
}
.list li.fav:hover:after {
  content: ' \2606';
}
</style>
</head>
<body>
<ul class="list">
  <li id="1">PostID1</li>
  <li id="2">PostID2</li>
  <li id="3">PostID3</li>
  <li id="4">PostID4</li>
  <li id="5">PostID5</li>
  <li id="6">PostID6</li>
</ul>
<script>
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
  document.getElementById(favorite).className = 'fav';
});
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
  var id = e.target.id,
      item = e.target,
      index = favorites.indexOf(id);
  // return if target doesn't have an id (shouldn't happen)
  if (!id) return;
  // item is not favorite
  if (index == -1) {
    favorites.push(id);
    item.className = 'fav';
  // item is already favorite
  } else {
    favorites.splice(index, 1);
    item.className = '';
  }
  // store array in local storage
  localStorage.setItem('favorites', JSON.stringify(favorites));
});
// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage
</script>

</body>
</html>

它返回以下本地存储输入(如果我添加postID 1和2):

favorites ["1","2"]

我正在努力的是如何将数据传递给我的查询(显示AJAX,但是我不知道该怎么做),以显示帖子。

如果我手动粘贴值(请参见变量$ q,它可以工作,但我不知道如何使用简单的ajax来实现。

我希望传递传递的数据的帖子列表是see-saved-posts.php

<?php require('includes/config.php'); ?>
    <?php
        $q = ("1,2");

            try {

                $stmt = $db->query('SELECT postID, postTitle, postSlug, postDesc, postDate FROM blog_posts_seo WHERE postID IN ('.$q.')  ');
                while($row = $stmt->fetch()){

                    echo '<div>';
                        echo '<h1><a href="'.$row['postSlug'].'">'.$row['postTitle'].'</a></h1>';
                        echo '<p>Posted on '.date('jS M Y H:i:s', strtotime($row['postDate'])).' in ';

                            $stmt2 = $db->prepare('SELECT catTitle, catSlug FROM blog_cats, blog_post_cats WHERE blog_cats.catID = blog_post_cats.catID AND blog_post_cats.postID = :postID');
                            $stmt2->execute(array(':postID' => $row['postID']));

                            $catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC);

                            $links = array();
                            foreach ($catRow as $cat)
                            {
                                $links[] = "<a href='c-".$cat['catSlug']."'>".$cat['catTitle']."</a>";
                            }
                            echo implode(", ", $links);

                        echo '</p>';
                        echo '<p>'.$row['postDesc'].'</p>';             
                        echo '<p><a href="'.$row['postSlug'].'">Read More</a></p>';             
                    echo '</div>';

                }

            } catch(PDOException $e) {
                echo $e->getMessage();
            }
        ?>

先谢谢了。 P.s.我是这个社区的新手,但是已经使用了很多年。通常,我可以通过搜索功能找到答案,但是这次没有。

1 个答案:

答案 0 :(得分:0)

所以我创建了一个ID为save-posts的div。在这里将打印从AJAX调用中获取的已保存帖子。我创建了一个名为getPosts()的函数,该函数对see-saved-posts.php页面执行AJAX调用,并传递一个名为q的查询字符串,并带有喜欢的ID。我两次调用了getPosts函数,一次是在页面加载时,一次是在更新收藏夹时。您必须在see-saved-posts.php页面上进行的一个操作是通过执行以下操作从查询字符串中获取收藏夹ID:$q = $_GET['q'];

更新

我已经更新了功能,以便仅在有任何收藏夹时才进行AJAX调用。如果所有收藏夹都被删除,则将从页面上其余的收藏夹中删除。

<html>
<head>
    <style>
        .list li {
            cursor: pointer;
        }
        .list li:hover:after,
        .list li.fav:after {
            content: ' \2605';
            color: rgb(255, 203, 0);
        }
        .list li.fav:hover:after {
            content: ' \2606';
        }
    </style>
</head>
<body>
<ul class="list">
    <li id="1">PostID1</li>
    <li id="2">PostID2</li>
    <li id="3">PostID3</li>
    <li id="4">PostID4</li>
    <li id="5">PostID5</li>
    <li id="6">PostID6</li>
</ul>


<div id="saved-posts"></div>


<script>
    // get favorites from local storage or empty array
    var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
    // add class 'fav' to each favorite
    favorites.forEach(function(favorite) {
        document.getElementById(favorite).className = 'fav';
    });

    getPosts(); // calls AJAX to populate with saved posts

    // register click event listener
    document.querySelector('.list').addEventListener('click', function(e) {
        var id = e.target.id,
            item = e.target,
            index = favorites.indexOf(id);
        // return if target doesn't have an id (shouldn't happen)
        if (!id) return;
        // item is not favorite
        if (index == -1) {
            favorites.push(id);
            item.className = 'fav';
            // item is already favorite
        } else {
            favorites.splice(index, 1);
            item.className = '';
        }
        // store array in local storage
        localStorage.setItem('favorites', JSON.stringify(favorites));

        getPosts(); // Call AJAX to repopulate with saved post
    });
    // local storage stores strings so we use JSON to stringify for storage and parse to get out of storage

    function getPosts() {
        if (favorites.length) {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("saved-posts").innerHTML = this.responseText;
                }
            };
            xhttp.open("GET", "see-saved-posts.php?q=" + favorites, true);
            xhttp.send();
        } else {
            document.getElementById("saved-posts").innerHTML = "";
        }
    }
</script>

</body>
</html>