简体   繁体   中英

controller can't return result in JSON object in ajax response

I have to call and fetch data from rest API with in every second. So I call the method with time 1 sec. As follows.

var myVar = setInterval(function(){ getData1() }, 1000);

Following is my Javascript function which call 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);
         }
        });
}

This 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;
    }

If I run the program then jsp does not shows any alert. but if I change the return type of in controller to String then it shows proper JSON string in ajax response.

ie [{"sno":"3618","data":"01","datetime":"2017-04-05 12:33:26.266"}]

If i carry this, then I am unable to get data from JSON string.

please tell me what is my issue. or is there any other way to do this.?

You have json array

[{"sno":"3618","data":"01","datetime":"2017-04-05 12:33:26.266"}]

Then access it using index:

data[0].sno

Simply return a String from getDashboardData1()

And then in AJAX success callback:

JSON.parse(data)[0]['sno'];

please tell me what is my issue. or is there any other way to do this.?

You can't access attributes of a string literal, it has to be a json object .

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