jQuery中的Ajax Json Parse错误

时间:2014-11-18 21:34:10

标签: jquery ajax json

我从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":"约翰"" LAST_NAME":" Mkay" }]}

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

我使用过以下的jQuery lib版本

并获得相同的解析错误。

我还尝试将dataType更改为' Json',' text',' json / text'甚至删除dataType参数,没有任何工作。请让我知道如何解决此问题

4 个答案:

答案 0 :(得分:1)

通过添加

解决了问题
response.getWriter().write(myObj.toString());

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

答案 1 :(得分:0)

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

data: JSON.stringify(dataString),

答案 2 :(得分:0)

发布整个代码。 Ajax调用返回null 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);
        }
    }
}

答案 3 :(得分:0)

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

我不确定是否&#34; System.out.println(response.getContentType();&#34;很有用.. 试着评论!!