Why do not you return the data of the json?

0

I'm working with the autocomplete ui by categories, the data is sent normally and the query runs smoothly but in the search engine does not return the data of the json ... what I'm doing wrong and how can I fix it?

<%@ include file="../conectadb.jsp" %>
<%@ page language="java"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"     "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Basic Search</title>
<style type="text/css">
    .ui-autocomplete-category {
    font-weight: bold;
    padding: .2em .4em;
    margin: .8em 0 .2em;
    line-height: 1.5;
  }
</style>
 <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
        <link rel="stylesheet" href="/resources/demos/style.css" />

</head>
<body>

<script>
      $.widget("custom.catcomplete", $.ui.autocomplete, {
                _renderMenu : function(ul, items) {
                    var that = this, currentCategory = "";
                    $.each(items, function(index, item) {
                        if (item.category != currentCategory) {
                            ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
                            currentCategory = item.category;
                        }
                        that._renderItemData(ul, item);
                    });
                }
            });
</script>

<script type="text/javascript">
    $(function() {
    $( "#search" ).catcomplete({
        delay: 0,
        minLength: 3,
        source: function(request, response) {
        $.ajax({
         url : "getsearchjson.jsp",
         dataType : "json",
         data :"searchText=eric",
         success : function(data) {
            console.log(data);
      
                            } //success
                        });
    }
});
});
</script>

<p />

<div class="container well">
    <div class="row-fluid">
        <form action="search" method="get">
            <div class="input-append">
                <input type="text" name="query" id="search" placeholder="Search.."/>
                
            </div>

        </form>
    </div>
</div>

</body>
</html>
<%@ include file="../conectadb.jsp" %>
<% 
   response.setContentType("application/json");
    String term=request.getParameter("searchText");   
    
%>
[
<%
  COMANDO =   "SELECT ID, "+
       "ORDEN, "+
       "NOMBRE GRUPO, "+
       "CODIGO, "+
       "NOM_SERV(ID_SERVICIO) SERVICIO, "+
       "ID_SERVICIO "+
       "FROM CATALOGO_NIVEL"+
      "WHERE    (NOMBRE LIKE UPPER ('%"+term+"%') OR ID_SERVICIO = '"+term+"') ";
  rset = stmt.executeQuery(COMANDO);
  while(rset.next() ){
%>
    { label: "<%=rset.getString("SERVICIO")%>", category: "<%=rset.getString("GRUPO")%>"},
<%}%>    
     {label:"", category:""}

];
    
asked by Julio Cesar 03.01.2018 в 17:05
source

1 answer

0

Mmm, I understand that getsearchjson.jsp refers to the first code block of your question. If so, and if you say that the query is going well, I think that what you would need is to return the values of the query.

At the end of getsearchjson.jsp you should include the results of the query to the object response and make a flush() to return the results. According to how you have it right now, you make the call the query is executed, but since they are not included in the response object, they are lost.

Also, to mention that in my opinion it is not very good practice to make queries to BBDD directly from a jsp , you should have a Servlet to which the requests were made and there you perform all the logical operations that you need for that request .

I modify the code a bit and you tell me if it works for you.

<%@ include file="../conectadb.jsp" %>
<% 
   response.setContentType("application/json");
   response.setCharacterEncoding("UTF-8");
//En este objeto deberías incluir todos los valores que quieras que te devuelva una petición AJAX
   PrintWriter writer = response.getWriter();
   String term=request.getParameter("searchText");   

  String results="";
  String COMANDO =   "SELECT ID, "+
       "ORDEN, "+
       "NOMBRE GRUPO, "+
       "CODIGO, "+
       "NOM_SERV(ID_SERVICIO) SERVICIO, "+
       "ID_SERVICIO "+
       "FROM CATALOGO_NIVEL"+
      "WHERE    (NOMBRE LIKE UPPER ('%"+term+"%') OR ID_SERVICIO = '"+term+"') ";
  rset = stmt.executeQuery(COMANDO);
  while(rset.next() ){

    results+="{ 'label': '"+rset.getString("SERVICIO")+"', 'category': '"+rset.getString("GRUPO")+"'},"
}    

  writer.println(results);
  writer.flush();

%>

Note: It is possible that the returned data is not in the correct format for the ui.autocomplete at the moment, so that the request ajax returns something we are on the right track.

UPDATE

As I told you, I'll give you a simple example of Servlet

package tu.propio.paquete;

public class ExampleServlet extends HttpServlet {

    //Tus peticiones tipo POST entraran por aqui
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doPost(req, resp);
    }


    //Tus peticiones tipo GET entraran por aquí
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        //En este objeto deberías incluir todos los valores que quieras que 
        te devuelva una petición AJAX
        PrintWriter writer = response.getWriter();
        String term=request.getParameter("searchText");   

        String results="";
        String COMANDO =   "SELECT ID, "+
                "ORDEN, "+
                "NOMBRE GRUPO, "+
                "CODIGO, "+
                "NOM_SERV(ID_SERVICIO) SERVICIO, "+
                "ID_SERVICIO "+
                "FROM CATALOGO_NIVEL"+
                "WHERE    (NOMBRE LIKE UPPER ('%"+term+"%') OR ID_SERVICIO = 
                '"+term+"') ";
        rset = stmt.executeQuery(COMANDO);
        while(rset.next() ){

          results+="{ 'label': '"+rset.getString("SERVICIO")+"', 'category': 
          '"+rset.getString("GRUPO")+"'},"
        }    

        writer.println(results);
        writer.flush();
    }  
}

When you create a servlet , you must also declare it in the web.xml of your project:

<servlet>
    <servlet-name>exampleServlet</servlet-name>
    <servlet-class>tu.propio.paquete.ExampleServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>exampleServlet</servlet-name>
    <url-pattern>/exampleServlet</url-pattern>
  </servlet-mapping>

And your ajax request, you should change the url parameter by the servlet name

$.ajax({
     url : "getsearchjson.jsp",
     dataType : "json",
     data :"exampleServlet",
     success : function(data) {
          console.log(data);
     } //success
});
    
answered by 03.01.2018 в 19:23