Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

javascript - AJAX and Java - Update Stocks

I am building a stock-based trading application and I am using Yahoo finance to get the prices for stocks.

I would like the prices to be updated every 5 seconds without having to refresh the page. I need to implement this using AJAX

Java controller:

@GetMapping("/banking/stocks")
public String stocks(Model model) {

model.addAttribute("stock", new StockDto());
try {
    List<Stock> stocks = stockService.getDefaultStocks(getCurrentUser());
    model.addAttribute("stocks", stocks);

} catch (IOException e) {
    e.printStackTrace();
}
return "stocks.html";
}

HTML:

<tbody>
<tr th:each="stock : ${stocks}">
    <td th:text="'$'+${stock.getSymbol()}"></td>                                                    
    <td th:text="${stock.getName()}"></td>
    <td th:text="${stock.getQuote().getPrice()}"></td>
    <td
        th:class="${stock.getQuote().getChangeInPercent() > 0 ? 'text-success' : 'text-danger'}"
        th:text="${stock.getQuote().getChangeInPercent() + '%'} "></td>
    <td th:if="${stock.getDividend().getAnnualYield() != null}"
        th:text="${stock.getDividend().getAnnualYield() + '%'}">0.00%</td>
    <td th:if="${stock.getDividend().getAnnualYield() == null}">0.00%</td>
</tr>

How can I implement AJAX so that getPrice() is called every 5 seconds and updated on the page? This has been a major issue for me and I must fix it.

Thank you


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

thmyleaf is a template engine , so when the page has showed the value will be set if you want a dynamic price you should use Javascript to replace html content instead of thmyleaf

Here is a simple Demo

[Codepen](https://codepen.io/chawol/pen/oNzaXdg)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...