2016-05-14 133 views
0

使用Spring和Maven,我構建和部署一個WAR項目,當地的Tomcat服務器,當我使用瀏覽器訪問的API,它的工作原理:無法使用JQuery請求將GET API部署到本地Tomcat服務器?

http://localhost:8015/keystroke-backend/user 

我:

[{"id":1,"username":"bilal","password":"pass"}] 

但當我使用AJAX使用JQuery訪問它時,沒有發生任何事情:

$(document).ready(function() { 
// Event to check the input data 
$("#login-form").submit(function(e) { 
    e.preventDefault(); 

    $.ajax({ 
     url: "http://localhost:8015/keystroke-backend/user" 
    }).then(function(data) { 
     alert("success"); 
    }); 
}); 
}); 

沒有任何反應。

這是GET API:

@Controller 
@RequestMapping("/user") 
public class KeystrokeController { 

@RequestMapping(method = RequestMethod.GET) 
@ResponseBody 
public ResponseEntity<List<User>> doGetUsers() { 

    List<User> usersList = new ArrayList<User>(); 
    try { 
     // Get the list of users from the database 
     usersList = UsersDB.getDB().getUsers(); 
     return new ResponseEntity<List<User>>(usersList, HttpStatus.OK); 
    } catch (Exception e) { 
     return new ResponseEntity<List<User>>(usersList, HttpStatus.NOT_ACCEPTABLE); 
    } 
} 
} 

我看到這個錯誤從控制檯:

XMLHttpRequest cannot load http://localhost:8080/testing-client/test/server-status/1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. 

需要注意的是,當我使用相同的代碼到別的訪問像下面這樣:

 url: "http://rest-service.guides.spring.io/greeting" 

它的工作原理。任何想法 ?

+0

發表您的控制器的方法 – Lucky

+0

@Lucky,我剛剛更新的問題 –

回答

0

在Ajax請求中添加內容類型可解決問題。

$("#login-form").submit(function(e) { 
    e.preventDefault(); 

    $.ajax({ 
     url: "http://localhost:8015/keystroke-backend/user", 
     contentType:"application/json" 
    }).then(function(data) { 
     alert("success"); 
    }); 
}); 
0

將您的輸入類型更改爲按鈕不提交,並在此處更改。在從不使用按鈕類型提交阿賈克斯。

$("#login-form").click(function(e) { 
+0

這是一樣的,也許這個問題是不相關的JQuery的,但使用本地Tomcat服務器,因爲當我使用相同的代碼,請求公衆API,它的工作原理。 –

+0

這不是tomcat問題,你可以使用瀏覽器訪問API, –