2017-09-10 11 views
-1

我正在關注此主題上的官方Spring文檔https://spring.io/guides/gs/consuming-rest-jquery/#_create_the_application_page如何在Spring Boot中使用ajax(jQuery)的REST服務?

也許還有其他東西被省略/缺失,但我無法讓它與我一起工作(Intellij,SpringBoot)。

我有完全相同的Greeting(來自他們的回購https://github.com/spring-guides/gs-rest-service/tree/master/complete/src/main/java/hello)GreetingController類,後者應該返回JSON數據。兩個控制器分開測試,運行良好。我的「index.html」和「hello.js」也被複制到tee。

但據我所知,爲了讓它工作,需要將客戶端重定向到這個「index.html」頁面,所以爲此我添加了另一個控制器。

最後,完整的項目結構:

src 
|--main 
    |---java 
     |---com.example.demo 
      |---controller 
       GreetingController.java 
       ClientController.java 
      |---model 
       Greeting.java 
     DemoApplication.java 
    |---resources 
     |---static.js 
      hello.js 
     |---templates 
      index.html 
     application.properties 

hello.js全文:

$(document).ready(function() { 
$.ajax({ 
    url: 'https://localhost:8080/greeting' 
}).then(function(data) { 
    $('.greeting-id').append(data.id); 
    $('.greeting-content').append(data.content); 
}); 

});

的index.html:

<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    <title>Hello jQuery</title> 
 

 
    <!--alt+enter to download the library in case it's not there--> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
 
    <script src="../static/hello.js"></script> 
 
</head> 
 

 
<body> 
 
<div> 
 
    <p class="greeting-id">The ID is </p> 
 
    <p class="greeting-content">The content is </p> 
 
</div> 
 
</body> 
 
</html>

正如你所看到的,hello.js具有以下功能:

url: 'https://localhost:8080/greeting' 

據我看到的,這是應該訪問這個地址,收到的響應將由GreetingController提供,然後解析爲一個JSON對象。但我只得到:

ID是
內容是

有什麼不對?本教程的唯一區別是我擁有自己的常用Spring控制器而不是Groovy。我還需要什麼來將它們全部粘在一起成功?

+0

控制檯中的任何錯誤?任何錯誤的服務器端?當你去那個網址時會發生什麼? – Janar

+0

@Janar不,沒有錯誤信息。當我去/問候時,我得到一個JSON字符串,當我用「index.html」進入頁面時,我只看到這兩行。似乎他們之間沒有映射和jQuery結果。 – mohican93

+0

@downvoter你到底還不清楚什麼? – mohican93

回答

1

在評論中澄清說,沒有找到JavaScript文件。爲了解決這個問題,你必須

  1. 更改腳本位置<script src="hello.js"></script>春季以來啓動查找靜態文件在src /主/資源/默認
  2. 靜態同樣的URL必須是HTTP,而不是HTTPS。
相關問題