[英]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.