javascript - 使用 php 和 javascript 向 api 发送消息
问题描述
在 JavaScript 中,创建一个文本输入和一个提交按钮。单击提交按钮时将文本字段的内容发送到 API。仅当它包含至少 1 个字符时才执行此操作。
我有一个文本字段和 sumbit 按钮,但是如何使用查询与 api 建立连接,以及如何确保它仅在需要至少 1 个字符时才向 api 发送内容?
解决方案
如果没有您的任何代码,真的很难猜出您尝试了什么。但无论如何,这是我的方法。
首先监听点击事件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
})
}
推荐阅读
- relational-database - 将具有 2 个实体之间的 2 个关系的 ER 图转换为 RM 模式
- jenkins - 基于隐藏文件是否存在的条件阶段
- node.js - 如何使用 stream.write 将密码发送到 ssh2 会话中的 ttys0 会话
- amazon-web-services - 我们计算的请求签名与您提供的签名不匹配。检查您从 Salesforce 到 amazon s3 的密钥和签名方法
- r - ggpaired (boxplot) 错误地配对数据点
- angular - 在 *ngIf 中加载动态组件 - createComponent 未定义
- vb.net - DateTime.Now = 无法提供值:找不到主机值
- selenium-webdriver - Selenium Chrome WebDriver 在 .NetCore 3.0 上抛出空异常
- excel - Excel 打开时如何禁用 Worksheet.Change 事件?然后在宏运行后重新启用它
- c++ - 以下代码中的变量 b 是什么以及 c++ 中联合的可能好处是什么?