使用jQuery调用REST服务时发生Uncaught ReferenceError

Uncaught ReferenceError when calling REST Service using jQuery

本文关键字:Uncaught ReferenceError 服务 jQuery 调用 REST 使用      更新时间:2023-09-26

我对web服务真的很陌生,所以我很感激这里的任何帮助。我已经使用Spring引导创建了一个RESTful web服务。我的web服务的代码很简单,因为我只是在测试:

@RestController
public class MainController {   
    @RequestMapping("/test")
    public String getStringTest(@RequestParam(value="name", defaultValue="Test") String name){
        System.out.println("Name received: " + name);
        return "HelloTest: " + name;
    }
}

部署web服务后,我可以使用以下方式访问它:http://localhost:8080/imagesTest我在浏览器中得到了"HelloTest"字符串,所以它运行得很好。但问题是,当我试图在网页中使用jQuery访问它时,它不起作用。这是页面:

<html>
 <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
 </head>
 <body>
  <p id="info"></p>
 </body>
</html>
<script>
 $(document).ready(function(){
    $.ajax({
        type: 'GET',
        dataType: 'jsonp',
        url: "http://localhost:8080/test?name=Gabriel",
        success: function(data){
            alert("Success: " + data);
        },
        error: function(){
            alert("Something went wrong.");
        }
    });
 })
</script>

当我执行页面时,我在控制台中收到以下错误消息:

未捕获的ReferenceError:HelloTest未定义(匿名函数)@图像测试?callback=jQuery1113027941066049970686_1447350578572&amp_=1447350578573:1

如果能在这方面提供任何帮助,我将不胜感激,这样我就能了解到底发生了什么

提前感谢您的帮助。

dataType: 'jsonp'>告诉jQuery期望JSONP,但是返回一个普通字符串"HelloTest: Gabriel"

dataType更改为更合适的,例如"text"(或完全删除)

$.ajax({
    type: 'GET',
    dataType: 'text',
    url: "http://localhost:8080/test?name=Gabriel",
    success: function(data){
        alert("Success: " + data);
    },
    error: function(){
        alert("Something went wrong.");
    }
});

可能的值列在$.ajax方法的api文档中