【问题标题】:Uncaught ReferenceError when calling REST Service using jQuery使用 jQuery 调用 REST 服务时未捕获的 ReferenceError
【发布时间】:2015-11-12 18:03:05
【问题描述】:

我真的是网络服务的新手,所以我很感激这里的任何帮助。我使用 Spring-boot 创建了一个 RESTful 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 未定义(匿名函数) @imagesTest?callback=jQuery1113027941066049970686_1447350578572&_=1447350578573:1

非常感谢您对此提供任何帮助,以便我了解实际情况。

提前感谢您的帮助。

【问题讨论】:

  • 您告诉 jQuery ajax 请求必须期待可执行的 Javascript,但您返回的是字符串 "HelloTest: Gabriel"
  • 谢谢安德烈亚斯。亲,能不能说的具体点?我是网络服务的新手。所以你是说我不能指望在成功函数的“数据”变量中捕获字符串?我对此不是很熟悉,抱歉。
  • dataType 属性更改为更合适的值。在这种情况下,我会选择"text" 或完全删除它。有关可能值的列表,请参阅api documentation

标签: javascript jquery spring rest


【解决方案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 documentation

【讨论】:

  • 谢谢安德烈斯。我已经尝试了这两个选项,删除它并使用您发布的示例。现在我得到一个不同的错误:XMLHttpRequest cannot load localhost:8080/test?name=Gabriel。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'null' 不允许访问。你能就此提出建议吗?再次感谢。
  • 如果您也可以发布错误,那将非常有帮助;-)
  • 谢谢安德烈亚斯。这是我的浏览器中出现的唯一错误,我使用的是 Google Chrome 作为我的浏览器。这是错误:“XMLHttpRequest cannot load localhost:8080/test?name=Gabriel. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' 因此不允许访问。”。我真的不知道会有什么问题。如果可行,我还使用完整的 Java 代码更新了问题。
  • 这是 Chrome 的一项安全功能。这将解决问题:stackoverflow.com/questions/8456538/…
  • 谢谢安德烈亚斯。没错,这是 Chrome 的问题。我使用 IE 11 测试了我的代码,它运行良好。你完全解决了我的问题。谢谢。
猜你喜欢
  • 2022-08-08
  • 2018-10-17
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
相关资源
最近更新 更多