AJAX не отображает json значение ключа массива, если в массиве json только один элемент из сервлета - PullRequest
1 голос
/ 01 марта 2020

Моя 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();
            });
        });

Он также ничего не печатает в консоли

Это мой сервлет

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!!!

1 Ответ

0 голосов
/ 01 марта 2020

Поскольку в json array имеется только один элемент, вам не нужно, чтобы l oop - $.each l oop, вы можете напрямую получить доступ ко всем элементам, используя responseJson[0]['keyname']. Также в своем предыдущем коде, когда вы использовали responseJson[0] в $.each l oop все значения получали 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...