简体   繁体   中英

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. 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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