Android httpservice和ajax

时间:2012-03-27 00:09:15

标签: android ajax jquery httpservice

我在Android设备上有一个httpservice:

/*some code*/
private static final String COMMAND_PATTERN = "/Commands/*";

...

registry.register(COMMAND_PATTERN, new ExecuteCommandHandler(context));

@Override
public void handle(HttpRequest request, HttpResponse response,
    HttpContext httpContext) throws HttpException, IOException {
    Log.e("", "INSIDE executor HANDLER");   
    String responseJSONString = "{\"result\":\"ok\"}";
    if (request instanceof HttpEntityEnclosingRequest) {
        responseJSONString="{\"result\":\"success!\"}";                                 
    }
    else responseJSONString="{\"result\":\"not instance of HttpEntityEnclosingRequest\"}";      

    final String jsonMessage = responseJSONString;
    HttpEntity entity = new EntityTemplate(new ContentProducer() {
        public void writeTo(final OutputStream outstream) throws IOException {
            Log.e("",jsonMessage);
            OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");             
            writer.write(jsonMessage);
            writer.flush();
        }
    });

    response.setEntity(entity); 
}   

我尝试使用ajax:

var ajx = $.getJSON('http://127.0.0.1:6789/Commands/');   
ajx.success(function(data){ 
    alert(data.result) 
}).error(function(data){ 
    alert('error') //IT HAPPENS EVERY TIME!!!
    alert(data.result) //EMPTY!!!
})

LogCat说:

03-26 23:24:53.447: ERROR/(4506): INSIDE executor HANDLER
03-26 23:24:53.487: ERROR/(4506): {"result":"not instance of HttpEntityEnclosingRequest"}

但是没关系!问题是ajax总是返回'错误'!也许我错过了什么。感谢

1 个答案:

答案 0 :(得分:0)

要在javascript中接收JSON,您需要以下内容:

$.getJSON('http://127.0.0.1:6789/Commands/', function(data) {
    if(data && data.result) {
        //OK
        console.log(data.result);
    } else {
        //Data error
        console.log('Data error');
    }
}).error(function(data) {
    //Timeout or whatever
    console.log('Timeout or whatever');
    console.log(data);
}).complete(function(){
    //Always call this at the end of the request
    console.log('Completed');
});