简体   繁体   中英

JSON object not being returned by jsp page

I was trying to return a JSON Object from this jsp page.But I dont know why Its not providing the required results.Here is my jsp page :

<%@page import="net.sf.json.JSONException"%>
<%@page import="net.sf.json.JSONArray"%>
<%@page import="net.sf.json.JSONObject"%>
<%@page contentType="application/json" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="application/json; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%

            JSONObject json      = new JSONObject();
            JSONArray  employeeslist = new JSONArray();
            JSONObject employee;
            try
            {
                int count = 15;

                for (int i=0 ; i<count ; i++)
                {
                    employee = new JSONObject();
                    employee.put("name"     , "Decepticons" + i);
                    employee.put("id"        , "1999" + i);

                    employeeslist.add(employee);
                 }
                json.put("Employeeslist", employeeslist);
            }
                catch (JSONException jse)
                { 

                }

            out.write(json.toString());
    %>
</body>
</html>

Please help me to find error in this code.

My ajax calling this jsp :

<script type="text/javascript">
$(document).ready(function() {
    $("input[type=button]").click(function () {
        $.ajax({
        url: 'ValidEmployeeList.jsp',
        dataType: 'json',
        success: function(data) {
            //alert(data);
            alert(JSON.stringify(data));
        },
         error: function() {
            alert('error');
        }
    });

    });
});
</script>

The json variable is never assigned beyond creating the new, empty, JSONObject. You only use employee and employeeslist. But you never print those out.

You mix Json content type with html format. Try removing html tags at start and end:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="application/json; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>

And

</body>
</html>

Finally do not ever use empty catch block. You might miss some important exception that is real cause.

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