Languages
[Edit]
PL

React - AJAX - metoda GET

3 points
Created by:
Violetd
835

W tym artykule chcielibyśmy pokazać, jak wykonać proste żądanie AJAX w React.

Używamy hooka React.useState do przechowywania odpowiedzi z serwera. Metoda fetch przenosi pathdo zasobu, który chcemy pobrać, następnie metoda .text() konwertuje otrzymany z serwera obiekt data na tekst, a wtedy metoda setResponse ustawia wartość stanu response.

Uruchamialny przykład:

// ONLINE-RUNNER:browser;

// Uwaga: Odkomentuj poniższe linijki podczas pracy z kompilatorem JSX:
// import React from "react";
// import ReactDOM from "react-dom";

const App = () => {
  const [response, setResponse] = React.useState();
  React.useEffect(() => {
    const requestText = 'hello';
    fetch(`/examples/echo?text=${encodeURIComponent(requestText)}`)
      .then(response => response.text())
      .then(responseText => {
        setResponse(`Response: ${responseText}`);
      })
      .catch(error => {
        setResponse('Request error!');
      });
  }, []);
  return (
    <div>{response}</div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App/>, root );

Przykład metody GET - Spring MVC

Logikę po stronie serwera, która może obsługiwać żądania z powyższego przykładu, możemy napisać za pomocą frameworku Spring .

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class EchoGetController {

    @RequestMapping(value = "/examples/echo", method = RequestMethod.GET)
    @ResponseBody
    public String makeGetEcho(@RequestParam("text") String text) {
        return text;
    }
}

Zobacz również

  1. JavaScript Ajax GET request with Java Spring MVC controller (ang)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS (PL)

React - AJAX - metoda GET
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join