英文:
How to get response back from the REST API and perform actions from jquery ajax call?
问题
我正在学习JS和jQuery,并尝试构建一个登录页面,在提供应用程序URL的凭据后,我应该得到一个响应,然后我应该能够相应地执行操作。
类似于:如果响应是"success",那么我应该得到一个成功的提示,并重定向到另一个页面(不太清楚如何做),如果响应是"fail",我应该弹出一个提示。
以下是我js文件中相关的代码片段:
$.ajax({
url: "http://localhost:8588/api/userLogin",
type: "POST",
data: credentials,
dataType: "json",
contentType: 'application/json',
success: function(response) {
alert(response);
}
});
以及我的Java控制器方法片段,带有@RestController注解:
@PostMapping(value = "/userLogin", consumes = "application/json")
public String userLogin(@RequestBody UserRequest userRequest) {
System.out.println(userRequest.getUserId() + " " + userRequest.getPassword());
User user = userService.getUser(userRequest);
return (user != null) ? "success" : "fail";
}
我没有收到任何错误
我能够调用API,但在UI上没有收到响应。我漏掉了什么?
英文:
I am learning JS, jquery, and trying to build a login page and after giving the credentials to my application URL I should get a response back and I should be able to perform actions accordingly.
Something like: if the response is "success" then I should get an alert for success and redirect to another page (not sure how to do that) and if the response is "fail" I should throw an alert.
Below is the relevant snippet from my js file:
$.ajax({
url: "http://localhost:8588/api/userLogin",
type: "POST",
data: credentials,
dataType: "json",
contentType: 'application/json',
success: function(response) {
alert(response);
}
});
And my java controller method snipped annotated with @RestController:
@PostMapping(value = "/userLogin", consumes = "application/json")
public String userLogin(@RequestBody UserRequest userRequest) {
System.out.println(userRequest.getUserId()+ " "+ userRequest.getPassword());
User user = userService.getUser(userRequest);
return (user != null) ? "succeess" : "fail";
}
I am not getting any error
I am able to call the API but not getting the response back on UI. What am I missing?
答案1
得分: 1
我已经采用了你的代码,并模拟了类似你的简单情况。大部分代码看起来都是正确的,但正如你所说,控制台中没有错误消息,也没有响应给客户端,所以问题肯定出在某个地方。你在这里没有指定某些事项,所以为了其他人更好地理解,我假设 UserRequest
如下:
public class UserRequest {
public String username;
public String password;
}
对于 ajax 请求中的 data
,我使用如下形式:
JSON.stringify({username: "developer", password: "pass"})
现在,在客户端端口,我得到了带有成功消息的 200 响应代码。如果在尝试了这个之后出现任何错误,请告诉我。
英文:
I've taken your code and simulated simple case like yours. Most of the code looks right but as you've said there are no errors in the console and no response to client so there's problem got to be somewhere. There are certain things you've not specified here, so for more context for other people I am assuming UserRequest
as
public class UserRequest {
public String username;
public String password;
}
and for the ajax request data
I'm using
JSON.stringify({username: "developer", password:"pass"})
Now, I'm getting 200 response code with success message in alert at client side. Let me know if any error pops up after trying this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论