简体   繁体   English

控制器无法在ajax响应中的JSON对象中返回结果

[英]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. 我必须每秒调用一次并从rest API中获取数据。 So I call the method with time 1 sec. 所以我以1秒的时间调用该方法。 As follows. 如下。

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

Following is my Javascript function which call the controller. 以下是我的Javascript函数,该函数调用控制器。

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. 如果我运行程序,则jsp不会显示任何警报。 but if I change the return type of in controller to String then it shows proper JSON string in ajax response. 但是如果我将in控制器的返回类型更改为String,那么它会在ajax响应中显示正确的JSON字符串。

ie [{"sno":"3618","data":"01","datetime":"2017-04-05 12:33:26.266"}] [{"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. 如果携带此文件,则无法从JSON字符串获取数据。

please tell me what is my issue. 请告诉我我的问题是什么。 or is there any other way to do this.? 还是有其他方法可以做到这一点?

You have json array 你有json数组

[{"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() 只需从getDashboardData1()返回一个字符串

And then in AJAX success callback: 然后在AJAX中成功回调:

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 . 您无法访问string文字的属性,它必须是json object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM