How to reload a HTML table without refreshing the whole page while working with Spring MVC

强颜欢笑 提交于 2019-12-10 18:15:07

问题


I am using Spring MVC , example.jsp file with Javascript.
I have been stuck on this for a long time.

Is it possible to use Javascript to laod new data from DB into HTML tables without refreshing the whole page?

I just don't want my whole page being replaced when new data is loaded into table with some event.


回答1:


If you want to reload a part of you page using JavaScript, basically AJAX.
This is how you should do it.

Client Side

Let's assume that you're using jQuery as a JavaScript Framework.
You'll need to use jQuery.ajax() in the Client Side.

var successHandler = function( data, textStatus, jqXHR ) {
  // After success reload table with JavaScript
  // based on data...
};

var errorHandler = function( jqXHR, textStatus, errorThrown ) {
  // Error handler. AJAX request failed.
  // 404 or KO from server...
  alert('Something bad happened while reloading the table.');
};

var reloadData = function() { 
  // Process your request
  var request = new Object();
  request.id = 'some id'; // some data

  // Make the AJAX call
  jQuery.ajax({
    type       : 'POST',
    url        : 'http://domain/context/reload-data-url',
    contentType: 'application/json',
    data       : JSON.stringify(request)
    success    : successHandler,
    error      : errorHandler
  });
};

Call the reloadData() function when you need to reload the table.

Server Side

You're using Spring MVC. Then your Controller should look like:

 // Spring MVC Controller
 @Controller
 public class ReloadDataController {

   // Request Mapping
   @RequestMapping(value = '/reload-data-url', method = RequestMethod.POST)
   @ResponseBody
   public ResponseEntity<String> processReloadData(@RequestBody String body) {

     // Get your request
     JSONObject request = new JSONObject(body);
     String id = request.getString("id"); // Here the value is 'some id'

     // Get the new data in a JSONObject
     JSONObject response = new JSONObject();
     // build the response...

     // Send the response back to your client
     HttpHeaders headers = new HttpHeaders();
     headers.add("Content-Type", "application/json; charset=utf-8");
     return new ResponseEntity<String>(response.toString(),
                headers, HttpStatus.OK);
   }

 }

You don't have to use JSON but I think this is the best way. Hope this will help you.



来源:https://stackoverflow.com/questions/12458540/how-to-reload-a-html-table-without-refreshing-the-whole-page-while-working-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!