如果来自servlet的json数组中只有一个元素,则AJAX不会显示json数组键值

问题描述 投票:1回答:1

我的AJAX函数如果json数组中有1个以上的元素,则显示列表实际上,我想从组织中搜索候选数据并将其打印到jsp页面。但是,当搜索结果来自一个组织的一个以上候选者时,则工作正常,但在json数组中仅包含一个元素时,效果不佳。

$("#searchbtn").click(function(event) {
            $('#loadingarea').show();
            arr.length = 0;
            names = "";
            total_fees = 0;
            $("#paymentForm").hide();
            $("#idbox").val("");
            $("#name").val("");
            $("#totalcostbox").val("");
            $("#countrytable").empty();
            var org_name = $("#org_name").val();
                jQuery.get('PaymentCandidates',
                    {org_name:org_name}, function(responseJson)
                {
                    console.log("HI Response is coming!!! :::"+responseJson);
                    var str = '<tr>\n' +
                        '<th>Select</th>\n' +
                        '<th>Name</th>\n' +
                        '<th>Stream</th>\n' +
                        '<th>Phase</th>\n' +
                        '<th>ExamType</th>\n' +
                        '<th>ExamDate</th>\n' +
                        '<th>Training Date (from)</th>\n' +
                        '<th>Training Date (to)</th>\n' +
                        '<th>Fees</th>\n' +
                        '<th>View</th>\n'+
                        '</tr>';
                    console.log("Collecting reponse from PaymentCandidates::::");
                    if(responseJson.length>0) {
                        $("#loadingarea").hide();
                        console.log("Total Entries::::" + responseJson.length);
                        //$("#countrytable").empty();
                        var table1 = $("#countrytable");
                        if (responseJson.length===1) {
                            $.each(responseJson[0], function (key, value) {
                                var json = JSON.parse(JSON.stringify(responseJson.toString()));
                                examtype = (value['examtype']);
                                stream = (value['stream']);
                                selected_name = (value['name'].toString());
                                if (examtype === "Exam") {
                                    cost = 1000;
                                } else if (examtype === "Training") {
                                    if (stream === "PCB") {
                                        cost = 20000;
                                    } else {
                                        cost = 60000;
                                    }
                                } else {
                                    cost = 0;
                                }
                                str += '<tr><td style="font-size: 25px"><input name=' + selected_name + ' type="checkbox" id=' + (value['id']) + ' value=' + cost + ' onchange="onCheckBoxChanged(this.id,this.value,this.name)"></td>';
                                str += '<td>' + (value['name']) + '</td>';
                                str += '<td>' + (value['stream']) + '</td>';
                                str += '<td>' + (value['phase']) + '</td>';
                                str += '<td>' + (value['examtype']) + '</td>';
                                str += '<td>' + (value['examdate']) + '</td>';
                                str += '<td>' + (value['training_from_date']) + '</td>';
                                str += '<td>' + (value['training_to_date']) + '</td>';
                                str += '<td>' + cost + '</td>';
                                str += '<td> <a class="button view" target="_blank" href=viewDetailedCandidate.jsp?' + (value['id']) + '>View Candidate Details</a></td></tr>';
                                $("#countrytable").append(str);
                            });

                        } else {
                            $("#loadingarea").hide();
                            $.each(responseJson, function (key, value) {
                                var json = JSON.parse(JSON.stringify(responseJson.toString()));
                                depositbal=(value['balance']);
                                if(depositbal>0){
                                    $("#usethisbal").show();
                                }
                                else{
                                    $("#usethisbal").hide();
                                }
                                $("#balancebox").val(depositbal);
                                examtype = (value['examtype']);
                                stream = (value['stream']);
                                selected_name = (value['name'].toString());
                                if (examtype === "Exam") {
                                    cost = 1000;
                                } else if (examtype === "Training") {
                                    if (stream === "PCB") {
                                        cost = 20000;
                                    } else {
                                        cost = 60000;
                                    }
                                } else {
                                    cost = 0;
                                }
                                str += '<tr><td style="font-size: 25px"><input name=' + selected_name + ' type="checkbox" id=' + (value['id']) + ' value=' + cost + ' onchange="onCheckBoxChanged(this.id,this.value,this.name)"></td>';
                                str += '<td>' + (value['name']) + '</td>';
                                str += '<td>' + (value['stream']) + '</td>';
                                str += '<td>' + (value['phase']) + '</td>';
                                str += '<td>' + (value['examtype']) + '</td>';
                                str += '<td>' + (value['examdate']) + '</td>';
                                str += '<td>' + (value['training_from_date']) + '</td>';
                                str += '<td>' + (value['training_to_date']) + '</td>';
                                str += '<td>' + cost + '</td>';
                                str += '<td> <a class="button view" target="_blank" href=viewDetailedCandidate.jsp?' + (value['id']) + '>View Candidate Details</a></td></tr>';
                            });
                            $("#countrytable").append(str);
                        }
                    }
                    else{
                        console.log("JSON Array Fetch Null....");
                    }

                });
                $("#tablediv").show();
            });
        });

它也不会在控制台中打印任何内容

这是我的servlet

import com.google.gson.Gson;
import com.google.gson.Gson;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;

@WebServlet("/PaymentCandidates")
public class PaymentCandidates extends HttpServlet {
Gson gson = new Gson();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String org_name=req.getParameter("org_name");
    System.out.println("ORG_NAME:"+org_name);
    //fetch Candidates from db
    ArrayList<Candidates> candidatesList = new ArrayList<>();
    PrintWriter pw=resp.getWriter();
    try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection connCandidate = null,connDeposit=null;
        System.out.println(":::CONNECTING TO CANDIDATES DB::::");
        connCandidate = DriverManager.getConnection("jdbc:mysql://localhost:3306/candidate_db", "root", "");
        System.out.println("Connected to Candidates DB for PAYMENT::::$$$$$");
        Statement stmt=connCandidate.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM `candidate_details` WHERE isPayment_received=\"Not Yet\" ");
        while(rs.next()){
            if(rs.getString(6).toLowerCase().contains(org_name.toLowerCase())) {
                Candidates cd = new Candidates();
                System.out.println("NAME:" + rs.getString(2));
                connDeposit = DriverManager.getConnection("jdbc:mysql://localhost:3306/deposit_db", "root", "");
                Statement st1=connDeposit.createStatement();
                ResultSet resultSet=st1.executeQuery("SELECT * FROM deposit_details;");
                while(resultSet.next()) {
                    if (resultSet.getString(1).equals(rs.getString(5))) {
                        cd.setBalance(resultSet.getString(2));
                    }
                }
                if(cd.getBalance()==null){
                    cd.setBalance("0");
                }
                resultSet.close();
                st1.close();
                connDeposit.close();
                cd.setId(rs.getString(1));
                cd.setName(rs.getString(2));
                cd.setStream(rs.getString(7));
                cd.setPhase(rs.getString(8));
                cd.setExamtype(rs.getString(15));
                cd.setExamdate(rs.getString(17));
                cd.setTrainingfromdate(rs.getString(18));
                cd.setTrainingtodate(rs.getString(19));
                candidatesList.add(cd);
            }
        }
        if(!(candidatesList.size() > 1)){
            pw.println("<script type=\"text/javascript\">");
            pw.println("alert('No Candidates Found');");
            pw.println("location='fillPayment.jsp';");
            pw.println("</script>");
        }
        System.out.println("GSON Done:::");
        String jsonString=gson.toJson(candidatesList);
        System.out.println("JSON ELEMENT DONE::");
        System.out.println("JSON ARRAY:::"+jsonString);
        resp.setContentType("application/json");
        resp.getWriter().write(jsonString);
        System.out.println("JSON ARRAY WRITTEN!!!");
    }
    catch(SQLException | ClassNotFoundException ce){
        pw.println("-------ERROR IN PROCESSING PAYMENT-----");
        pw.println("Error is:"+ ce.getMessage());
    }

  }

}



***Servlet Output***
ORG_NAME:Evil Corporation
:::CONNECTING TO CANDIDATES DB::::
Connected to Candidates DB for PAYMENT::::$$$$$
NAME:Kaival Patel
GSON Done:::
JSON ELEMENT DONE::
JSON ARRAY::: 
[{"id":"1","name":"KaivalPatel",
"stream":"Ahmedabad","phase":"21","examtype":"8","examdate":"Exam",
"training_from_date":"No","training_to_date":"-","balance":"0"}]
JSON ARRAY WRITTEN!!!
jquery json ajax jsp servlets
1个回答
0
投票

由于json array中只有一个元素,所以您不需要循环通过$.each循环,您可以使用responseJson[0]['keyname']直接访问所有元素。此外,当您在[[ C0]循环所有值都为responseJson[0],因为jquery无法识别$.each。相反,您可以执行以下操作(我已删除了所有不相关的代码):

undefined
keys
© www.soinside.com 2019 - 2024. All rights reserved.