简体   繁体   English

浏览器尝试保存对AJAX请求的JSON响应,而不是处理它

[英]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 我正在尝试通过简单的登录页面将JSON和AJAX实施为MVC设计模式,但是出现错误

Here's my Login.jsp (View) : 这是我的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) : 这是我的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) : 这是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. 我正在尝试做的是一个登录页面,如果用户未输入正确的USERNAME和PASSWORD,则会出现警报。 What am i doing wrong? 我究竟做错了什么? When i ever i run the project this is the result 当我运行项目时,这就是结果
这是结果

I'm just new to AJAX and JSON . 我只是AJAXJSON新手。 For JSON i'm using GSON library 对于JSON我正在使用GSON

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. 乍一看,这应该可以工作,但是以某种方式,对setContentType的调用无效。

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 ,其Content Type应如下所示:

Content-Type: application/json

If that line is missing, set a break point in the line with response.setContentType() and look into the response. 如果缺少该行,请使用response.setContentType()在该行中设置一个断点,然后查看响应。 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 . 您没有提到登录成功还是失败时是否看到错误,而是您编写代码的方式,如果登录成功,则触发if(isValid)检查,从而导致转发对您的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. 因为您从javascript AJAX帖子中调用了该调用,所以如果servlet确实转发到MainPage.jsp ,则可能发生的情况是您的AJAX帖子正在获取该JSP的处理结果,而不是您认为正在发送的映射。 And the content type is probably not being set by MainPage.jsp to application/json . 而且, MainPage.jsp可能未将内容类型设置为application / json

Next time it happens, actually save the returned file and look into it to see what the content is. 下次发生这种情况时,请实际保存返回的文件,并查看其中的内容。

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

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