简体   繁体   中英

how can i fetch data without refresh page using javascript & django?

i am using django to make API and get data with javasctipt. first time i'm using javascript i don't have very good understanding with javasctipt. i want to get data without refreshing page i am using javacript to fetch data form API. my code is getting data from databse only when i refresh the page. is there way to get data without refreshing page? when anybody create new post then page automatically load the post in index page without refresh the page?

index.html

<script>
    const Story = document.getElementById('stories');
    const Url = 'http://localhost:8000/api/';

    async function getPosts() {
        await fetch(Url)
            .then((res) => res.json())
            .then((data) => {
                data.map((post, index) => {
                    Story.innerHTML += `
                <div class="card card-body mb-3">
                  <h3>${post.title}</h3>
                </div>
              `;
                });
            })
            .catch((err) => console.log(err))
    }
    var timer = setInterval(getPosts,3000)
    getPosts();
</script>

Without getting into the more complex world of things like WebSocket , the simplest way is to put getPosts(); into a setInterval and have it run the function every X seconds. This will rerun the function even if no new posts have been made but its the easiest.

The below code will run getPosts on load and every 3 seconds (3000 miliseconds)

<script>
    const Story = document.getElementById('stories');
    const Url = 'http://localhost:8000/api/';

    async function getPosts() {
        await fetch(Url)
            .then((res) => res.json())
            .then((data) => {
                Story.innerHTML = "";
                data.map((post, index) => {
                    Story.innerHTML += `
                <div class="card card-body mb-3">
                  <h3>${post.title}</h3>
                </div>
              `;
                });
            })
            .catch((err) => console.log(err))
    }

    var timer = setInterval(getPosts,3000)
    getPosts();
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM