weixin_33725270 2012-12-28 01:28 采纳率: 0%
浏览 47

Ajax致电Spring服务

I'm trying to make a simple ajax call to a spring REST service I have setup.

My controller is defined as follows:

@Controller
public class SongPlayerController {
    ....
    @RequestMapping(value = { "/ajax", "/ajax/" }, method = RequestMethod.GET)
    @ResponseBody
    public String ajax() {
        return "New Song URL";
    }
}

And then I have a simple html page with an ajax request:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<title>Insert title here</title>

<script type="text/javascript">
    function loadAjax() {
        $.ajax({
            type : "GET",
            url : "http://localhost:8080/song-player/ajax",
            data : "text",
            success : function(response) {
                $('#ajax').val(response);
            },
            error : function(e) {
                alert('Error: ' + e);
            }
        });
    }

    function getAjax() {
        $.getJSON('http://localhost:8080/song-player/ajax', function(data) {
            alert('Ajax data' + data);
        });
    }
</script>
</head>
<body>
    <button type="button" onclick="loadAjax()">Ajax Call</button>
    <div id="ajax">This will be an ajax call.</div>
</body>
</html>

But, neither using the $.ajax or $.getJSON are returning anything. When using the ajax call, I'm getting the error "Error: [object Object]".

However, I know that my controller is setup properly because I can hit my service and get a response by using the RESTClient Firefox add-on so I assume the problem is with how I'm handling the jQuery calls but this is my first attempt at using jQuery so I don't know what is wrong with it.

  • 写回答

4条回答 默认 最新

  • weixin_33724659 2012-12-28 01:33
    关注

    The string literal "New Song URL" is not valid JSON. Try returning this:

    @Controller
    public class SongPlayerController {
        @RequestMapping(value = { "/ajax", "/ajax/" }, method = RequestMethod.GET)
        @ResponseBody
        public String ajax() {
            return "{\"url\":\"New Song URL\"}";
        }
    }
    

    Then access this value as follows:

    function getAjax() {
        $.getJSON('http://localhost:8080/song-player/ajax', function(data) {
            alert('Ajax data' + data.url);
        });
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?