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