Search code examples
javajavascriptservletstitaniumappcelerator-mobile

Quick Java Servlet and HTTP Q (with Titanium Appcelerator)


I have created a basic Java Servlet page which just displays hello world

What im trying to learn and understand is how to basically pull the information down from a web server and display it on the mobile device (and then hopefully post information back up to the web page)

I have some sample code here, when the application runs there is no connection error everything goes through as planned, the alert message displays Hello World which im guessing is the 'this.response.text)

I have been reading through the documentation given from Appcelerator Titanium but find it hard to understand with the JSON files and parsing etc..

Q. so if anyone can help me understand how i can pull 'Hello World'' down from the servlet page and display maybe in a label/textfield thanks hopefully your answers will then help me understand how to take data from the mobile client and send to information to the web page

var xhr = Ti.Network.createHTTPClient({
onload : function(e){
    Ti.API.info('Received text: ' + this.responseText);
    alert(this.responseText);


},
onerror: function(e) {
    Ti.API.info('error, HTTP status = ' + this.status);
    alert('error');
},
timeout:5000
});

xhr.open("GET", "http://130.206.127.43:8080/HelloWorld");
xhr.send();

Solution

  • I think what you want is to return the results from your Java servlet as a JSON string so that you can read it properly in Titanium.

    Start by creating a Map or w/e with the information you want to return to the client.

    {message=Hello world, action=display, extra=extra}
    

    Then convert it to a JSON string (examples)

    Now in your Titanium application you can parse the result as JSON and use your returned info:

    onload : function(e){
        var result = JSON.parse(this.responseText);
        alert(result.message);
        alert(result.action);
        alert(result.extra);
    },
    

    EDIT: Replaced the eval