首页 > 解决方案 > 使用 php 和 javascript 向 api 发送消息

问题描述

在 JavaScript 中,创建一个文本输入和一个提交按钮。单击提交按钮时将文本字段的内容发送到 API。仅当它包含至少 1 个字符时才执行此操作。

我有一个文本字段和 sumbit 按钮,但是如何使用查询与 api 建立连接,以及如何确保它仅在需要至少 1 个字符时才向 api 发送内容?

标签: javascriptphp

解决方案


如果没有您的任何代码,真的很难猜出您尝试了什么。但无论如何,这是我的方法。

首先监听点击事件button

yourButton.addEventListener('click', fetchAPI);

然后执行必要的检查并查询 API

function fetchAPI() {
  // Check if the input has something in it
  if (yourTextField.value === '') return;
  
  // Change this to whatever your API expects
  const query = 'https://api.example.com/?text=${yourTextField.value}';
  
  // Use AJAX to query the API
  fetch(query, {
    method: 'POST', // Or GET
  })
    .then((response) => response.json()) // Only if the response is in JSON, otherwise use response.text()
    .then((data) => {
      // Handle the response
    })
  
}

推荐阅读