Zafu: KendoUI JSP autocomplete revisited


In Zafu: KendoUI JSP taglib + Couchbase (3) I have explained how to implement an autocomplete for accessing the name of the beers of Couchbase sample-beer database. That time I have used a pretty complex structure for mapping KendoUI filter.

But if the only thing that I need is sending whatever the user has typed so far, might not be worthwhile using such complex structure. If that’s your case, this is what you have to do.

Redefine parameterMap

In the previous post I have used the following function for generating the parameters to send to the server.

function kendoJson(d, t) {
    return "param=" + JSON.stringify(d);
}

Now, I have redefined it as:

function kendoJson(d, t) {
    return "name=" + d.filter.filters[0].value + "&limit=" + d.take;
}

I.e., only send the data typed so far as a parameter called name and limit as the number of results that is the value defined in kendo:dataSource JSP tag.

Get the parameters in the server

In the server now the parameters are much easier to retrieve since they arrive as two different parameters with the names name and limit.

String name = request.getParameter("name");
int limit = 10;
System.out.println("Limit:" + request.getParameter("limit"));
if (request.getParameter("limit") != null) {
    try {
        limit = Integer.parseInt(request.getParameter("limit"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

And then invoke the query as we explained in the last post:

Query query = new Query();
query.setIncludeDocs(false);
query.setStale(Stale.FALSE);
query.setDescending(false);
query.setReduce(false);
query.setSkip(0);
query.setLimit(limit);
query.setRangeStart(name)
ViewResponse result = client.query(view, query);
Iterator itr = result.iterator();
Advertisements

Formatting JSON object as string.


Just a little trick… when you need to format a JSON object for displaying it you might use JSON.stringify and there is a third argument that is the space. If you write JSON.stringify(obj, null, ‘\t’) if prints each element preceded by a tabulator.

The space might also be a number and then the text is indented with the specified number of white spaces at each level.

Example:

var obj = {
    field1: 123.5,
    field2: true,
    field3: "Hello, OnaBai!",
    field4: [ "Working", "in", "a", "cloud", "of", "documents" ],
    field5: {
        field51: "I'm nested"
    },
    field6: function() {
        alert("Hello, OnaBai");
    }
};
console.log(JSON.stringify(obj, null, 2));

Shows:

{
  "field1": 123.5,
  "field2": true,
  "field3": "Hello, OnaBai!",
  "field4": [
    "Working",
    "in",
    "a",
    "cloud",
    "of",
    "documents"
  ],
  "field5": {
    "field51": "I'm nested"
  }
} 

NOTE: As you can see functions are not displayed!!!

More information here and here.