当然可以!以下是一个示例,你可以将其插入到网页中的适当位置:

<button onclick='askQuestion()'>点击这里问问题</button>
<p id='answer'></p>

<script>
  function askQuestion() {
    const question = '你的问题在这里';
    fetch('/ask', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ question }),
    })
      .then(response => response.json())
      .then(data => {
        const answer = data.answer;
        document.getElementById('answer').innerHTML = answer;
      })
      .catch(error => {
        console.error('发生错误:', error);
      });
  }
</script>

上述代码创建了一个按钮,当用户点击按钮时,会触发JavaScript函数askQuestion()。该函数将问题发送到服务器上的/ask端点,然后将返回的答案显示在网页上的<p>元素中,该元素具有id='answer'

请确保将/ask端点的URL替换为你服务器上的实际端点。此外,你可能需要进行其他配置和安全性措施,例如对用户输入进行验证和防止XSS攻击。

如何在网页中插入一个带有文字的按钮并触发JavaScript函数

原文地址: https://www.cveoy.top/t/topic/UtA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录