简体   繁体   中英

Sending message to a api with php and javascript

In JavaScript, create a text input and a submit button. Send the content of the text field to the API when the submit button is clicked. Only do this if it contains at least 1 character.

I have a text field and sumbit button, but how do I make the connection with the api using a query and how can I make sure it only sends something to the api if it needs at least 1 charachter?

Without any of your code, it's really difficult to guess what you've tried. But anyway, here's my approach.

First listen for the click event on the button :

yourButton.addEventListener('click', fetchAPI);

Then perform the necessary checks and query the 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
    })
  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM