返回

按钮点击时请求 URL 无法更新?— 剖析原因及解决方案

javascript

按钮点击时请求 URL 无法更新的问题

简介

在 JavaScript 项目中,根据按钮点击事件动态更新请求 URL 可能是一个常见的任务。然而,有时我们可能会遇到按钮点击后 URL 无法更新的问题。本文将深入探究这一问题,提供解决方案,并探讨相关内容。

问题分析

在给定代码中,我们有一个 JavaScript 函数 myFunction,当用户点击 "Happy" 按钮时执行该函数。该函数的目的是将 endPoint 变量更新为 "happiness",然后调用 fetchQuoteOption 函数。

然而,从给定的代码中可以看出,fetchQuoteOption 函数直接从 apiUrlendPoint 变量中构建请求 URL。因此,当 myFunction 更新 endPoint 变量时,它并不会影响到 fetchQuoteOption 函数中使用的 URL。

解决方案

要解决此问题,我们需要确保在 myFunction 函数中更新 choiceUrl 变量,它是用于在 fetchQuoteOption 函数中构建请求 URL 的变量。修改后的代码如下:

function myFunction() {
  endPoint = 'happiness';
  choiceUrl = `${apiUrl}${endPoint}`; // 更新 choiceUrl
  fetchQuoteOption();
}

通过更新 choiceUrl 变量,我们确保了 fetchQuoteOption 函数将在下次调用时使用更新后的 URL。

完整代码

以下是完整修改后的代码:

let apiUrl = 'https://api.quotable.io/random?tags='
let happyUrl = 'happiness'
let endPoint = '';
let choiceUrl = `${apiUrl}${endPoint}`;
console.log(choiceUrl)

async function quoteOptions() {

  let quoteTypes = document.createElement('div');

  quoteTypes.innerHTML =
    `<div class='container2'>
    <p>Welcome! How are you feeling today?</p>
        <button id="happyBtn">Happy</button>
        <button id="motivationalBtn">Motivational</button>
        <button id="lovedBtn">Loved</button>
        <button id="humorousBtn">Silly</button>
      </div>`

  let content = document.querySelector('.container');
  content.appendChild(quoteTypes)

}
quoteOptions();

async function fetchQuoteOption() {

  try {

    const response = await fetch(`${apiUrl}${endPoint}`);
    const data = await response.json();
    console.log(data);
    return data;

    console.log(`Why is ${endPoint} not updating?`);

  } catch (error) {
    console.error('Error:', error);
  }

}

document.getElementById("happyBtn").addEventListener("click", myFunction);

function myFunction() {
  endPoint = 'happiness';
  choiceUrl = `${apiUrl}${endPoint}`; // 更新 choiceUrl
  fetchQuoteOption();
}

其他相关内容

  • 避免直接更新 URL :一般来说,应避免直接更新请求 URL,因为这可能会导致不一致和不可预测的结果。相反,我们应该使用中间变量(如 choiceUrl)来存储更新后的 URL。
  • 使用 URLSearchParams :URLSearchParams API 是一种更高级的方式,可以帮助我们构造和更新 URL 查询参数。我们可以使用 URLSearchParams 对象来创建和管理参数,然后将它们添加到 URL 中。
  • 调试和测试 :确保按钮点击后 URL 已正确更新非常重要。使用浏览器的开发工具或 console.log 语句来调试和测试您的代码。

常见问题解答

  1. 为什么直接更新 URL 会导致问题?
    直接更新 URL 会导致问题,因为它会影响其他依赖该 URL 的代码部分。例如,fetchQuoteOption 函数需要使用正确的 URL 才能获取数据。

  2. 如何防止这种情况再次发生?
    通过使用中间变量(如 choiceUrl)来存储更新后的 URL,我们可以防止这种情况再次发生。

  3. 是否存在其他更新 URL 的方法?
    是的,我们可以使用 URLSearchParams API 来构造和更新 URL 查询参数,这是一种更高级的方法。

  4. 如何确保更新后的 URL 已正确使用?
    使用浏览器的开发工具或 console.log 语句来调试和测试您的代码,以确保更新后的 URL 已正确使用。

  5. 如果我仍然遇到问题该怎么办?
    如果您仍然遇到问题,请联系开发人员社区或在 Stack Overflow 等网站上寻求帮助。