简体   繁体   中英

Submitting a From to a REST API using JQuery does not work

I have a REST API running and I am posting some data to it using JQuery.

This is how my JQuery code looks:

$(document).ready(function () {

    $('#login-form').submit(function () {

        var user = $('#uname').val();
        var pass = $('#pwd').val();

        alert('username = ' + user);
        alert('password = ' + pass);

        var JSONObject = { 'userName': user, 'password': pass };
        var jsonData = JSON.parse(JSONObject);

        $.ajax({
            url: 'http://127.0.0.1:8080/user/login',
            method: 'POST',
            data: { userName: user, password: pass },
            dataType: 'JSON',
            contentType: 'application/json',
            success: function (data, status, jqXHR) {
                //Do something
                console.log('data = ' + data);

            },
            error: function (jqXHR, status, errorThrown) {
                alert('error ' + errorThrown);

            }
        });

    });

});

However, this code is unable to access the API. I do not get the expected message in the server log. When the Submit button of the form is clicked, the browser gets reloaded and it shows the form inputs in the url. That is all.

My API is written using Java and this is the relevant method.

@RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public ResponseEntity<User> logUser(@RequestBody User user){

        User loggedUser = loginService.authenticateUser(user);

        if(loggedUser != null){
            System.out.println("User found");
            return new ResponseEntity<User>(loggedUser, HttpStatus.ACCEPTED);
        }else{
            //user does not exsits
            System.out.println("User not found");
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }

    }

I really can't understand what is wrong. No any error is shown. Can somebody point me out why this happens and how to fix this issue.

The issue is that the browser is reloading on submit event. You need to add preventDefault() method like this

$("#login-form").submit(function (event) {
      event.preventDefault()
      //further code here

This will prevent the browser from reloading

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