Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

Axiomatik avatar Axiomatik 2422 Точки

;-)

function attachEvents() {
    document.getElementById('btnLoadPosts').addEventListener('click', getAllPosts);
    document.getElementById('btnViewPost').addEventListener('click', displayPost);
}

attachEvents();

async function displayPost() {
    const titleElement = document.getElementById('post-title');
    const bodyElement = document.getElementById('post-body');
    const ulElement = document.getElementById('post-comments');
    const selectedId = document.getElementById('posts').value;
    titleElement.textContent = 'Loading...';
    bodyElement.textContent = '';

    ulElement.replaceChildren();

    const [post, comments] = await Promise.all([
        getPostById(selectedId),
        getCommentsbyPostId(selectedId),
    ]);

    titleElement.textContent = post.title;
    bodyElement.textContent = post.body;

    ulElement.replaceChildren();

    comments.forEach(c => {
        const liElement = document.createElement('li');
        liElement.textContent = c.text;
        ulElement.appendChild(liElement);
    })
}

async function getAllPosts() {
    const url = `http://localhost:3030/jsonstore/blog/posts`;
    const res = await fetch(url);
    const data = await res.json();
    const selectElement = document.getElementById('posts');

    selectElement.replaceChildren();

    Object.values(data).forEach(p => {
        const optionElement = document.createElement('option');
        optionElement.textContent = p.title;
        optionElement.value = p.id;
        selectElement.appendChild(optionElement);
    });
}

async function getPostById(postId) {
    const url = `http://localhost:3030/jsonstore/blog/posts/` + postId;
    const res = await fetch(url);
    const data = await res.json();

    return data;
}

async function getCommentsbyPostId(postId) {
    const url = `http://localhost:3030/jsonstore/blog/comments`;
    const res = await fetch(url);
    const data = await res.json();
    const comments = Object.values(data).filter((x) => x.postId == postId);

    return comments;
}

 

2
27/04/2023 10:22:26
inaivanova1990 avatar inaivanova1990 33 Точки

Благодаря за бързия отговор, но и твоят код дава 50 точки... На мен ми е интересно да разгледам решение, което дава максималният брой точки, за да си изясня какво пропускам. Явно има някакви допълнителни изисквания, които трябва да се съобразят...

0
Axiomatik avatar Axiomatik 2422 Точки

Ooops sorry. From all the solutions that I have for this exercise, they all gave 50% apparently - actually the trainer should finish up this one (not reply with "Ask people at discord...") and explain how to achieve 100%, since many students only have 50%.

Thanks to Nikolay for the 100% code =>

function attachEvents() {
    //Get DOM elements
    let postsSelect = document.querySelector('select#posts');
    let btnLoadPosts = document.getElementById('btnLoadPosts');
    let btnViewPost = document.getElementById('btnViewPost');
    let postTitle = document.getElementById('post-title');
    let postContent = document.getElementById('post-body');


    //Add event listeners
    btnLoadPosts.addEventListener('click', handleLoadPosts);
    btnViewPost.addEventListener('click', handleViewPost);
    let commonData;

    function handleLoadPosts() {
        //Get posts
        fetch('http://localhost:3030/jsonstore/blog/posts')
            .then(res => res.json())
            .then(data => addPosts(data));

        function addPosts(data) {
            commonData = data;

            postsSelect.innerHTML = '';

            for (let [id, postInfo] of Object.entries(data)) {
                //Create option
                let option = document.createElement('option');
                option.value = id;
                option.textContent = postInfo.title;
                option.dataset.body = postInfo.body;
                postsSelect.appendChild(option);
            }
        }
    }

    function handleViewPost() {
        //Get post id
        let selectedPostId = document.getElementById('posts').value;

        postTitle.textContent = commonData[selectedPostId].title;
        postContent.textContent = commonData[selectedPostId].body;


        //Fetch comments
        fetch('http://localhost:3030/jsonstore/blog/comments')
            .then(res => res.json())
            .then(data => handleComments(data));

        //Handle comments
        function handleComments(data) {
            let commentsUl = document.getElementById('post-comments');
            commentsUl.innerHTML = '';

            for (let [commentInfo] of Object.entries(data)) {
                if (commentInfo.postId == selectedPostId) {
                    //Create comment li
                    let li = document.createElement('li');
                    li.id = commentInfo.id
                    li.textContent = commentInfo.text;
                    commentsUl.appendChild(li);
                }
            }
        }
    }
}

attachEvents();

 

2
inaivanova1990 avatar inaivanova1990 33 Точки

Супер! Явно judge се сърди ако се правят повече заявки от зададеното.... Решението дава 100/100, след като поправих един ред от това, което ми прати последно, за дда закача правилно коментарите:

for (let [commentInfo] of Object.entries(data)) {

=> for (let commentInfo of Object.values(data))

Благодаря за решението!

 

 

 

 

 

2
adamusa avatar adamusa 2 Точки

I am really impressed with your article. The information you share will be an important document for me to learn more about this topic. mapquest driving directions

-1
victorpatrick avatar victorpatrick 7 Точки

Issue with comment iteration: In the handleComments function, the for...of loop is not correctly iterating over the comment entries. To fix this, you need to use destructuring assignment to separate the key and value in the loop. Bitlife  

-1
stipulaterooster avatar stipulaterooster 3 Точки

My geometry dash lite guess is that the trainer should finish this one (instead of saying, "Ask people at discord...") and explain how to get a perfect score of 100% using the solutions I have. For whatever reason, exceeding the predetermined number of requests causes the judge to become irate.

0
28/02/2024 10:39:55
bekean avatar bekean -2 Точки

Being a hit in this Drift Hunters game not only gives you bragging rights to everyone, but it also unlocks the drift cars of your dreams and makes it easy to change upgrades anytime you want.

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.