【问题标题】:AJAX doesn't display json array key value if there is only one element in json array from servlet如果 servlet 的 json 数组中只有一个元素,AJAX 不显示 json 数组键值
【发布时间】:2020-06-13 17:55:50
【问题描述】:

我的 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】:

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

    var responseJson = [{
      "id": "1",
      "name": "KaivalPatel",
      "stream": "Ahmedabad",
      "phase": "21",
      "examtype": "8",
      "examdate": "Exam",
      "training_from_date": "No",
      "training_to_date": "-",
      "balance": "0"
    }];
    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);
      var table1 = $("#countrytable");
      if (responseJson.length === 1) {
    
        examtype = (responseJson[0]['examtype']);
    
        stream = (responseJson[0]['stream']);
    
        selected_name = (responseJson[0]['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=' + (responseJson[0]['id']) + ' value=' + cost + ' onchange="onCheckBoxChanged(this.id,this.value,this.name)"></td>';
        str += '<td>' + (responseJson[0]['name']) + '</td>';
        str += '<td>' + (responseJson[0]['stream']) + '</td>';
        str += '<td>' + (responseJson[0]['phase']) + '</td>';
        str += '<td>' + (responseJson[0]['examtype']) + '</td>';
        str += '<td>' + (responseJson[0]['examdate']) + '</td>';
        str += '<td>' + (responseJson[0]['training_from_date']) + '</td>';
        str += '<td>' + (responseJson[0]['training_to_date']) + '</td>';
        str += '<td>' + cost + '</td>';
        str += '<td> <a class="button view" target="_blank" href=viewDetailedCandidate.jsp?' + (responseJson[0]['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....");
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table id="countrytable"></table>

    【讨论】:

    • 感谢斯瓦蒂的帮助!但问题出在 servlet 中,我通过 servlet 在 javascript 中调用,如果条件错误......这部分 if(!(candidatesList.size() > 1)){ pw.println(""); pw.println("alert('未找到候选人');"); pw.println("location='fillPayment.jsp';"); pw.println(""); }
    猜你喜欢
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多