سؤال

I'm trying to implement a simple autocomplet using jquery autocomplete, ajax, objectify and JSP. But the problem is that i can't do the query to response with a list of suggestion to send in json format to Jquery. How can I do that? This is my code:

function showData(value){ 
    $.ajax({
        url : "categoriaServlet?action=autoC&name="+value,
        type : "POST",
        async : false,
        success : function(data) {
            console.log(data);
            $("#nam").autocomplete(data);
    }
    });
}

And this is a piece of jsp code:

public void autoc(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String name = req.getParameter("name");
    System.out.println(name);
    ObjectifyService.register(Categoria.class);
    System.out.println(ofy().load().type(Categoria.class).filter("nome in", ofy().load().type(Categoria.class)).list());

So how can do correctly the query to send the list of suggestions? Thanks

هل كانت مفيدة؟

المحلول

I resolved. This is the code:

public void autoc(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException, JSONException {
    String name=req.getParameter("name");
    System.out.println(name);
    ObjectifyService.register(Categoria.class);
    System.out.println(ofy().load().type(Categoria.class).filter("nome in", ofy().load().type(Categoria.class)).list());
    System.out.println(ofy().load().type(Categoria.class).filter("nome", name).list());
    QueryResultIterable<Categoria> lista=ofy().load().type(Categoria.class).iterable();
    ArrayList<String> l= new ArrayList<String>();
    for(Categoria c : lista){
        l.add(c.getNome());
    }
    StringBuilder sb= new StringBuilder();
    ArrayList<String> l2= new ArrayList<String>();
    String search = name;
    sb.append("[");
    for(String str: l) {
        sb.append(str);
        sb.append("\"");
        if(str.trim().contains(search)){
           sb.append(str);
        sb.append("\"");
        sb.append(",");}
    }
    sb.append("\"");
    sb.append("\"");
    sb.append("]");


    resp.setContentType("application/json");  // Set content type of the response so that jQuery knows what it can expect.
    resp.setCharacterEncoding("UTF-8");
    resp.getWriter().write(sb.toString());
}

And this my script:

<script type="text/javascript">
function showData(value) {
    var x=null;
    $.ajax({
        url : "categoriaServlet?action=autoC&name=" + value,
        type : "POST",
        async : false,
        success : function(data) {
            console.log(data);
            x = data;

        }
    });
    $("#nam").autocomplete({ source: x
    });
};

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top