[英]Sending message to a api with php and javascript
在 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
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.