【问题标题】:Ajax Json Parse Error in jQueryjQuery中的Ajax Json解析错误
【发布时间】:2014-11-18 21:34:09
【问题描述】:

我从 Ajax 调用中收到以下解析错误。 "SyntaxError: JSON.parse: JSON 数据的第 1 行第 1 列的数据意外结束"

               $.ajax({
                        type: "POST",
                        url: "QueryOrder",
                        data: dataString,
                        dataType: "json",
                        success: function(
                            data) {;
                            alert("I am in Success");
                            alert(data);

                        },
                        error: function(jqXHR,
                            textStatus,
                            errorThrown) {
                            alert("Error Return from Ajax");
                            alert(jqXHR
                                .getResponseHeader('Content-Type'));
                            alert(jqXHR.responseText);
                            alert(jqXHR);
                            alert(errorThrown);
                            alert(textStatus);
                        }
                    }); //end of Ajax call

我已经验证了在 servlet 代码中生成的 json 对象及其有效

{"orderObj":[{"FIRST_NAME":"John","LAST_NAME":"Mkay"}]}

和 response.setContentType("application/json");用于设置响应。

我已经尝试过以下 jQuery lib 版本

并得到相同的解析 eof 错误。

我还尝试将 dataType 更改为“Json”、“text”、“json/text”,甚至删除了 dataType 参数,但没有任何效果。请告诉我如何解决此问题

【问题讨论】:

  • success: function( data) {;那个分号会报错
  • 服务器响应头在说什么?响应预览是否显示 json?
  • 是的,响应显示内容类型为 json *************************** Content-Length 0 Content-类型 application/json 日期 Tue, 18 Nov 2014 21:36:59 GMT 服务器 Apache-Coyote/1.1
  • 只是因为它确实发生在我身上,请注意 dataType 是“json”而不是“application/json”作为标准 mime 类型。

标签: jquery ajax json


【解决方案1】:

问题通过添加解决了

response.getWriter().write(myObj.toString());

到 servlet 代码。感谢大家的支持。

【讨论】:

    【解决方案2】:

    我认为您的问题是您必须使用适当的 json 序列化程序将数据发送到服务器:

    data: JSON.stringify(dataString),
    

    【讨论】:

    • 我已经尝试过了,但得到了同样的错误。问题在于 Ajax 正在接收的 Json 数据。不知何故,即使它的有效 json 对象也无法解析它
    • 我明白了。您可以在此处检查您的 json 是否有效:jsonlint.com 如果有效,请尝试其他浏览器或清理缓存。
    • 我确实使用 jsonlint.com 验证了 json,它是有效的。在与 json 相关的 ajax 调用时,是否需要使用特定的 jQuery.js lib 版本?我已经尝试过 1.7.2/jquery.js 和 jquery-1.10.2.js 并且都给出了 json 解析错误
    • 你熟悉getJSON()方法吗?您可以尝试这种方法,看看问题是否仍然存在:api.jquery.com/jquery.getjson
    • 我试过 getJSON() 但现在 function(data) 返回的数据为空。我可以看到servlet中形成的JSONObject是有效的但没有返回到getJSON()
    【解决方案3】:

    发布整个代码。 Ajax 调用返回空 JSON 对象

    ******************HTML************************************ ********

        <!doctype html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>jQuery UI Dialog - Modal form</title>
    <link rel="stylesheet"
        href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"
        type="text/javascript"></script>
    <link rel="stylesheet" href="/resources/demos/style.css">
    <style>
    body {
        font-size: 62.5%;
    }
    
    h1 {
        font-size: 1.2em;
        margin: .6em 0;
    }
    
    div#orders-contain {
        width: 450px;
        margin: 30px 0;
    }
    
    div#orders-contain table {
        margin: 1em 0;
        border-collapse: collapse;
        width: 150%;
    }
    
    div#orders-contain table td, div#orders-contain table th {
        border: 1px solid #eee;
        padding: .6em 10px;
        text-align: left;
    }
    }
    </style>
    <script>
        $(document).ready(function() {
            $("#query-order").click(function(e) {
                dataString = "countryCode=";
                alert("on Load");
                 $.ajax({
                        type: "POST",
                        url: "QueryOrder",
                        data: dataString,
                        dataType: "json",
                        success: function(
                            data) {
                            alert("I am in Success");
                            alert(data);
                        },
                        error: function(jqXHR,
                            textStatus,
                            errorThrown) {
                            alert("Error Return from Ajax");
                            alert(jqXHR
                                .getResponseHeader('Content-Type'));
                            alert(jqXHR.responseText);
                            alert(jqXHR);
                            alert(errorThrown);
                            alert(textStatus);
                        }
                    }); //end of Ajax call
            }); // end of click function
        });
    </script>
    </head>
    <body>
        <div id="orders-contain" class="ui-widget">
            <h1>Orders:</h1>
            <table id="Orders" class="ui-widget ui-widget-content">
                <thead>
                    <tr class="ui-widget-header ">
                        <th>Order Number</th>
                        <th>Customer Number</th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Date of Order</th>
                        <th>Address</th>
                        <th>Order Total</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                </tbody>
            </table>
        </div>
        <button id="query-order">Query Orders</button>
    </body>
    </html>
    

    *****************************Servlet 代码**************** ********

    package com.order.pkg;
    
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.ArrayList;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.google.gson.*;
    
    public class QueryOrder extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        /**
         * @see HttpServlet#HttpServlet()
         */
        public QueryOrder() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
         *      response)
         */
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
               doPost(request,response);
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
         *      response)
         */ 
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("application/json");        
    
            response.setHeader("Cache-control", "no-cache, no-store");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Expires", "-1");
    
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type");
            response.setHeader("Access-Control-Max-Age", "86400"); 
            try {
                Class.forName("oracle.jdbc.OracleDriver");
                System.out.println("Driver loaded");
    
                String url = "jdbc:oracle:thin:@localhost:1521:xe";
                String user = "dbtest";
                String pwd = "dbtest";
                Connection DB_mobile_conn = DriverManager.getConnection(url, user,
                        pwd);
                System.out.println("Database Connect ok");
    
                String query = "select * from ORDER_HEADERS";
    
                ArrayList<Order> orderList = new ArrayList<Order>();
    
    
                if (query != null) {
                    Statement query_stmt = DB_mobile_conn.createStatement();
                    ResultSet query_rs = query_stmt.executeQuery(query);
                    while (query_rs.next()) {
                        Order orderobj = new Order();
                        orderobj.setFIRST_NAME(query_rs.getString("FIRST_NAME").trim());
                        orderobj.setLAST_NAME(query_rs.getString("LAST_NAME").trim());
                        orderList.add(orderobj);
                    }
                    query_rs.close();
                    query_stmt.close();
                }
    
                Gson gson = new Gson();
                JsonObject myObj = new JsonObject();
                JsonElement orderObj = gson.toJsonTree(orderList);
                myObj.add("orderObj", orderObj);
                System.out.println(myObj);      
    
                System.out.println(response.getContentType());              
    
            } catch (Exception exp) {
                System.out.println("Exception = " + exp);
            }
        }
    }
    

    【讨论】:

      【解决方案4】:

      使用 out.println(myObj) 而不是 system.out.println(myObj) 作为 sop 打印到控制台,并且您的 ajax 调用返回而没有响应!

      我不确定“System.out.println(response.getContentType();”是否有用.. 试试评论吧!!

      【讨论】:

        猜你喜欢
        • 2012-10-13
        • 2017-07-31
        • 1970-01-01
        • 2012-05-14
        • 2013-07-23
        • 1970-01-01
        • 2014-08-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多