我正在使用 Spring MVC,example.jsp 文件和 Javascript。
我已经坚持了很长时间。
是否可以在不刷新整个页面的情况下使用 Javascript 将新数据从数据库加载到 HTML 表格中?
我只是不想在新数据通过某些事件加载到表中时替换我的整个页面。
最佳答案
如果您想使用 JavaScript 重新加载页面的一部分,基本上是 AJAX。
这就是您应该做的。
客户端
假设您使用的是 jQuery作为 JavaScript 框架。
您需要使用 jQuery.ajax()在客户端。
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
});
};
需要重新加载表格时调用reloadData()
函数。
服务器端
您正在使用 Spring MVC。那么你的 Controller 应该是这样的:
// 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);
}
}
您不必使用 JSON,但我认为这是最好的方法。 希望这对您有所帮助。
关于javascript - 使用 Spring MVC 时如何在不刷新整个页面的情况下重新加载 HTML 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12458540/