My task requires me to continuously call and fetch data from a REST API every second. To achieve this, I am calling the method with a time interval of 1 second as shown below:
var myVar = setInterval(function(){ getData1() }, 1000);
Below is the JavaScript function responsible for calling the controller:
function getData1(){
var url=CONTEXT_ROOT+"/login/getdashboarddata1";
$.ajax({
type: "POST",
url: url,
contentType: "application/json",
dataType: "json",
data:{},
success: function(data){
alert(data);
},
error: function(e){
//alert(e);
}
});
}
Here is my controller code:
@RequestMapping(value="/getdashboarddata1", method=RequestMethod.POST)
public JSONObject @ResponseBody getDashboardData1() throws JsonParseException, JsonMappingException, NullPointerException{
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/r_f22bc0ac1fe48bce/dataService/lastdata/";
String user = restTemplate.getForObject(url, String.class);
System.out.println("user: "+user);
JSONObject obj = null;
try {
obj = new JSONObject(user);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
When running the program, no alerts are displayed in the JSP. However, if I change the return type in the controller to String, it properly shows the JSON string response in AJAX.
For example,
[{"sno":"3618","data":"01","datetime":"2017-04-05 12:33:26.266"}]
Despite doing this, I am still unable to retrieve data from the JSON string. Please help me identify the issue or suggest another way to accomplish this task.