2016-05-14 131 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, –