简体   繁体   English

如何从 REST API 获取响应并从 jquery ajax 调用中执行操作?

[英]How to get response back from the REST API and perform actions from jquery ajax call?

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.我正在学习 JS、jquery,并尝试构建一个登录页面,在向我的应用程序 URL 提供凭据后,我应该得到响应,我应该能够执行相应的操作。 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:以下是我的 js 文件中的相关片段:

        $.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:我的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) ? "succeess" : "fail";
      }

I am not getting any error I am able to call the API but not getting the response back on UI.我没有收到任何错误 我可以调用 API 但没有在 UI 上得到响应。 What am I missing?我错过了什么?

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有些事情您没有在此处指定,因此对于其他人的更多上下文,我假设UserRequest

public class UserRequest {
    public String username;
    public String password;
}

and for the ajax request data I'm using以及我正在使用的 ajax 请求data

JSON.stringify({username: "developer", password:"pass"})

Now, I'm getting 200 response code with success message in alert at client side.现在,我在客户端收到 200 条带有成功消息的响应代码。 Let me know if any error pops up after trying this.如果尝试此操作后出现任何错误,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM