简体   繁体   中英

Browser tries to save JSON response to AJAX request instead of processing it

I'm trying to implement JSON and AJAX to MVC design pattern through simple login page, but i'm having an error

Here's my Login.jsp (View) :

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Test Page</title>
<script src="../js/jquery-1.10.1.min.js" ></script>
<script src="../js/data_handler.js" ></script>
</head>
<body>
    <form action="LoginController" method="post" id="loginForm">
        <!-- Login body -->
        <table>
            <tr>
                <td><label for="userName">Username:</label></td>
                <td><input type="text" name="userName" id="userName" /></td>
            </tr>
            <tr>
                <td><label for="password">Password:</label></td>
                <td><input type="password" name="password" id="password" /></td>
            </tr>
            <tr>
                <td><input type="submit" /></td>
            </tr>
        </table>
        <hr />
        <p id="displayName" /> 
    </form>
</body>
</html>

Here's my LoginController (Controller) :

 protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException,
        IOException
    {
        Map<String, Object> map = new HashMap<String, Object>(); // variable that will hold data to be parsed to JSON

        UserDAO userDAO = new UserDAO(); // instantiate database

        String userName = request.getParameter( "userName" ); // get userName String from the Login.jsp
        String password = request.getParameter( "password" ); // get password String from the Login.jsp
        boolean isValid = userDAO.authenticate( userName, password );
        map.put( "isValid", isValid );
        if( isValid ) // validate userName and password
        {

            UserModel userModel = userDAO.getUserDetails( userName ); // get userModel that correspond to userName parameter

            request.getSession().setAttribute( "userName", userName ); // set SESSION REQUEST to be forward to MainPage.jsp
            request.setAttribute( "userDetails", userModel ); // set REQUEST to be forward to MainPage.jsp

            RequestDispatcher rd = request.getRequestDispatcher( "MainPage.jsp" );
            rd.forward( request, response ); // forward request to MainPage.jsp
            return;
        }
        else
        {
            map.put( "userName", userName );
            write( response, map );
        }
    }

    /**
     * @param response
     * @param map contains data to parse to JSON
     * @throws IOException
     */
    private void write( HttpServletResponse response, Map<String, Object> map ) throws IOException
    {
        response.setContentType( "application/json" );
        response.setCharacterEncoding( "UTF-8" );
        response.getWriter().write( new Gson().toJson( map ) );
    }

Here's the data_handler.js (AJAX) :

$(document).ready(function(){
    $('#loginForm').submit(function(){
        $.ajax({
            url: 'LoginController',
            type: 'POST',
            dataType: 'json',
            data: $('loginForm').serialize(),
            success: function(data){
                alert("hello");
            }
        });
        return false;
    });         
});

What i'm trying to do is a login page that if the user didn't enter a proper USERNAME and PASSWORD an alert will appear. What am i doing wrong? When i ever i run the project this is the result
这是结果

I'm just new to AJAX and JSON . For JSON i'm using GSON library

As you can see in the dialog, the file type is "Unknown File Type".

In your code, I can see that you set the content type:

response.setContentType( "application/json" );

and you're doing this before you start to write the data of the response.

At first glance, this should work but somehow, the call to setContentType has no effect.

Go to the debug tools of your browser and look into the response headers. You can find a line Content Type in there which should look like this:

Content-Type: application/json

If that line is missing, set a break point in the line with response.setContentType() and look into the response. There should be a stream in there. Make sure that stream is still empty.

You don't mention whether or not you see the error if the login is successful or on failure, but the way you have the code written, if the login is successful you are triggering your if(isValid) check which results in a forwarding of the request to your MainPage.jsp .

Because you invoked the call from a javascript AJAX post, if the servlet does forward to the MainPage.jsp what is likely happening is that your AJAX post is getting back the processed results of that JSP, not the map you think you are sending. And the content type is probably not being set by MainPage.jsp to application/json .

Next time it happens, actually save the returned file and look into it to see what the content is.

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