跨调查页面保存调查的答案和进度

问题描述 投票:0回答:1

我需要帮助!我正在尝试调试我的代码,我的目标是获取附加到 URL 的答案,当用户导航到调查的下一页时,答案和进度将转移到该页面,用户可以选择他们想要的位置留下答案和进展。本地存储/会话存储不是一个选项。

我尝试使用 URLSearchParams: get() 方法。 // 对于第一页

 let progress = 0;
    let answers = {};



    // Fetch data for the second page questions
    if (window.location.href==="https://careerassess.mysites.io/?page_id=25") {
        const fetchedDataPromise = fetch('https://services.onetcenter.org/ws/mnm/interestprofiler/questions?client=careerspring', {
            headers: {
                'Accept': 'application/json'
            }
        })
        .then(response => response.text())
        .then(content => {
            try {
                return JSON.parse(content);
            } catch (error) {
                console.error('Error parsing JSON data:', error);
                throw error;
            }
        })
        .catch(error => {
            console.error('Error fetching data:', error);
            throw error;
        });

        fetchedDataPromise.then(data => {
            const fetchedData = data;

            const fieldsets = document.querySelectorAll('fieldset');
            let answeredQuestions = 0;

            for (let i = 0; i < fetchedData.question.length; i++) {
                const question = fetchedData.question[i];
                const answerOptions = fetchedData.answer_options.answer_option;

                const fieldset = fieldsets[i];
                const legend = fieldset.querySelector('legend');
                const dataContainer = fieldset.querySelector('#data-container');

                legend.textContent = `Question ${question.index}: ${question.text}`;

                const questionContainer = document.createElement('div');
                questionContainer.innerHTML = '<p>';

                for (const option of answerOptions) {
                    const label = document.createElement('label');
                    label.innerHTML = `<br><input name="q${question.index}" type="radio" value="${option.value}"><br>${option.name}<br>`;
                    questionContainer.appendChild(label);
                }

                dataContainer.appendChild(questionContainer);

                    // Attach event listeners to radio buttons
  const questionRadios = fieldset.querySelectorAll('input[type="radio"]');
                    questionRadios.forEach(radio => {
                        radio.addEventListener('click', function() {
                            const answerNumber = this.value;
                            const questionIndex = this.name.substring(1);

                            if (answers[questionIndex] !== answerNumber) {
                                if (!answers[questionIndex]) {
                                    answeredQuestions++;
                                }
                                answers[questionIndex] = answerNumber;
                                console.log('Answers:', answers); // Log the answers object
                                updateURL();
                                updateProgressBar();
                                onEveryPage();
                                getUserAnswerOnCurrentPage();
                            }
                        });
                    });
                }

                
  function fetchParams() {
  // Create a new URLSearchParams object
  let params = new URLSearchParams(window.location.href);

  // Get the value of the answers query parameter
  let newAnswers = params.get("answers");
      

  // Return the value of the answers query parameter
  return newAnswers;
}

function getUserAnswerOnCurrentPage() {
  // Get the current question index from the 'name' attribute of the HTML element
  const currentQuestionIndex = parseInt(this.name.substring(1));

  // Find the radio button that is currently selected within the same parent element
  const selectedRadioButton = this.parentElement.querySelector('input[type="radio"]:checked');

  // Get the value of the selected radio button, which represents the user's answer
  const answer = selectedRadioButton.value;

  return {
    questionIndex: currentQuestionIndex,
    answer: answer
  };
}

function onEveryPage() {
    // Assume answersFromPreviousPage is fetched and stored as an object
    const answersFromPreviousPage = fetchParams();

    // Assume userAnswer is retrieved when the user answers a question
    const userAnswer = getUserAnswerOnCurrentPage();

    // Store userAnswer in userAnswersOnCurrentPage object
    const userAnswersOnCurrentPage = {}; // Initialize an empty object or use existing data structure
    userAnswersOnCurrentPage[userAnswer.questionIndex] = userAnswer.answer;

    // Merge answersFromPreviousPage and userAnswersOnCurrentPage
    const currentAnswersParam = Object.assign({}, answersFromPreviousPage, userAnswersOnCurrentPage);

    // Convert the merged object into a URL parameter string
    const currentAnswersQueryParam = Object.entries(currentAnswersParam)
        .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
        .join('&');

    // Use the currentAnswersQueryParam in the URL for navigation or updating
    const updatedURL = window.location.href.split('?')[0] + '?' + currentAnswersQueryParam;

}


                
                const progressBar = document.getElementById('progress');

                function updateProgressBar() {
                    const totalQuestions = fetchedData.question.length;
                    answeredQuestions = Object.keys(answers).length;
                    progress = (answeredQuestions / totalQuestions) * 20;
                    console.log('Total', totalQuestions);
                    console.log('Answered', answeredQuestions);
                    progressBar.style.width = progress + '%';
                    console.log('Progress', progress);
                }

                function updateURL() {
                    const selectedAnswers = Object.values(answers);
                    console.log('Selected', selectedAnswers)
                    const currentURL = window.location.href;
                    console.log('currentURL', currentURL)
                    const newURL = '?answers=' + selectedAnswers.join('');
                    console.log('NewUrl',newURL)
                }

            });
    }
</script>



//for the second page

function fetchParams() {
              // Create a new URLSearchParams object
              let params = new URLSearchParams(window.location.href);

              // Get the value of the answers query parameter
              let newAnswers = params.get("answers");

              // Return the value of the answers query parameter
              return newAnswers;
        }

function getUserAnswerOnCurrentPage() {
  // Get the current question index
  const currentQuestionIndex = parseInt(this.name.substring(1));

  // Get the radio button that is currently selected
  const selectedRadioButton = this.parentElement.querySelector('input[type="radio"]:checked');

  // Get the value of the selected radio button
  const answer = selectedRadioButton.value;

  return {
    questionIndex: currentQuestionIndex,
    answer: answer
  };
}

function onEveryPage() {
    // Assume answersFromPreviousPage is fetched and stored as an object
    const answersFromPreviousPage = fetchParams();

    // Assume userAnswer is retrieved when the user answers a question
    const userAnswer = getUserAnswerOnCurrentPage();

    // Store userAnswer in userAnswersOnCurrentPage object
    const userAnswersOnCurrentPage = {}; // Initialize an empty object or use existing data structure
    userAnswersOnCurrentPage[userAnswer.questionIndex] = userAnswer.answer;

    // Merge answersFromPreviousPage and userAnswersOnCurrentPage
    const currentAnswersParam = Object.assign({}, answersFromPreviousPage, userAnswersOnCurrentPage);

    // Convert the merged object into a URL parameter string
    const currentAnswersQueryParam = Object.entries(currentAnswersParam)
        .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
        .join('&');

    // Use the currentAnswersQueryParam in the URL for navigation or updating
    const updatedURL = window.location.href.split('?')[0] + '?' + currentAnswersQueryParam;

}


                
                const progressBar = document.getElementById('progress');

                function updateProgressBar() {
                    const totalQuestions = fetchedData.question.length;
                    answeredQuestions = Object.keys(answers).length;
                    progress = (answeredQuestions / totalQuestions) * 20;
                    console.log('Total', totalQuestions);
                    console.log('Answered', answeredQuestions);
                    progressBar.style.width = progress + '%';
                }

                function updateURL() {
                   const selectedAnswers = Object.values(answers);
                   console.log('Selected', selectedAnswers)
                   const currentURL = window.location.href;
                   console.log('currentURL', currentURL)
                   const newURL = currentURL  + selectedAnswers.join('');
                }
            });
        }

javascript debugging storage
1个回答
0
投票

好吧,由于您无法使用本地存储来保存用户的答案,那么您可以将答案和进度附加到 URL 作为查询参数。当用户导航到下一页时,进度和答案将通过读取 URL 参数传输到该页面。使用

URLSearchParams
即可。 这只是一个示例,因为我没有阅读您的所有代码,您可以根据您的需要进行调整:

// Get the current URL
const url = new URL(window.location.href);

// Create a new URLSearchParams object from the query string of the current URL
const params = new URLSearchParams(url.search);

// Get the value of the 'answers' query parameter
const answers = params.get('answers');

// Parse the value of the 'answers' query parameter as a JSON object
const parsedAnswers = JSON.parse(answers);

// Update the value of the 'answers' query parameter with new answers
params.set('answers', JSON.stringify(newAnswers));

// Update the query string of the current URL with the new value of the 'answers' query parameter
url.search = params.toString();

// Navigate to the next page of the survey using the updated URL
window.location.href = url.toString();

从这个例子中我假设您有办法设置和获取

newAnswer
的值,这是调查当前页面的改编答案。

© www.soinside.com 2019 - 2024. All rights reserved.