简体   繁体   中英

Display returned Java object in jsp page using Ajax

I have a jsp page which contains html which I am using as my view, a rest endpoint which I am querying using Ajax to get the @ResponseBody and a script tag in jsp which will call the Ajax function every few seconds. The Ajax call is currently working and is at least calling the endpoint on schedule.

Currently when I navigate to the endpoint in my browser I am shown the JSON response from Java.

  1. How do I get this to return my actual JSP page with html?
  2. When the Ajax call returns and assigns the value of the response to the wrapper variable, how do I tell the page to update each field?

Some code snippets of my controller and JSP.

Controller

@Controller
@RequestMapping("/")
public class BackgroundJobController {

    private BackgroundJobServiceImpl backgroundJobService = new BackgroundJobServiceImpl();

    @RequestMapping(value = "/home", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody Wrapper getHome() {
        Wrapper wrapper = new Wrapper();
        wrapper.setMessage("done");
        return wrapper;
    }
}

Home.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="message" value="${wrapper.message}"></c:set>

<script type="text/javascript"
        src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
  function getUpdate() {
    $.ajax({
      url : '/home',
      success : function(data) {
        $('#wrapper').html(data);
      }
    });
  }
</script>

<script type="text/javascript">
  var intervalId = 0;
  intervalId = setInterval(getUpdate, 3000);
</script>

  <Table class="messageTable">
    <c:if test="${not empty message}">
        <tr><td>${message}</td></tr>
    </c:if>
  </Table>

I have managed to get it worked with help from the comment from Jozef.

I moved the <script> tags to the end of the body and added dataType: 'json' to my ajax request so the result was already parsed.

Once the success method is called I could then use

      for (var i = 0; i < 9; i++) {
        uat += '<tr><td>' + message[i] + '</td>';
        uat += '</tr>';
      }
      document.getElementById("uatTable").innerHTML = uat;

to build the table and document.getElementById("ID").innerHTML = data to display the results in the hmtl table.

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