$ .get返回空响应

时间:2018-04-18 06:04:34

标签: jquery

我正在调用以下jquery调用

var url = "demo/getResponseData"
$.get(url,function(responseData, status){
 console.log("dtFetched:",responseData);
 alert("status" + status);
});

后端弹簧启动代码如下

@RequestMapping(path="demo/getResponseData")
    public JSONObject getResponseData()  throws IOException, JSONException{
        System.out.println("================================Called from JavaScript");
        HttpClientManager httpClientMgr = new HttpClientManager();
        List<JSONObject> responseString= httpClientMgr.getResponseData();
        JSONObject object = new JSONObject();
         object.put("data", responseString);
        System.out.println("============OUTPUT====================" + responseString);
        //return responseString;
        return object;
    }

我能够在java控制台中看到输出,但是'responseData'是空的。代码有什么问题?

2 个答案:

答案 0 :(得分:1)

您正在为javascript中的响应记录错误的变量

var url = "demo/getResponseData"
$.get(url,function(responseData, status){
 console.log("dtFetched:",responseData); // <- fix this line
 alert("status" + status);
})

答案 1 :(得分:0)

尝试添加dataType

function random_number($maxlength = 17) 
    { 
        $chary = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o","p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z","0", "1", "2", "3", "4", "5", "6", "7", "8", "9","A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"); 
        $return_str = ""; 
        for ( $x=0; $x<=$maxlength; $x++ ) 
            { 
                $return_str .= $chary[rand(0, count($chary)-1)]; 
            } 
        return $return_str; 
    } 

    $random=random_number(); 
    $file_name = strip_tags($_FILES['upload_file']['name']); //File Name 
    $vpb_file_name = $random.$file_name;

还将@ResponseBody添加到控制器

var url = "demo/getResponseData"
$.get(url,function(responseData, status){
    console.log("dtFetched:",responseData);
    alert("status" + status);
}, "json");

同样根据this answer in so,最好将JSON作为字符串返回。

public @ResponseBody JSONObject getResponseData()