2013-03-23 67 views
3

我请求浏览器使用ajax将JSON数据发布到流v0.5.5服务器。在服务器端,我如何从ajax请求接收数据?如何访问从浏览器发送到Rikulo Steam服务器的POST数据

我的客户:(谷歌浏览器)

void ajaxSendJSON() { 
    HttpRequest request = new HttpRequest(); // create a new XHR 

    // add an event handler that is called when the request finishes 
    request.onReadyStateChange.listen((_) { 
    if (request.readyState == HttpRequest.DONE && 
     (request.status == 200 || request.status == 0)) { 
     // data saved OK. 
     print(request.responseText); // output the response from the server 
    } 
    }); 

    // POST the data to the server 
    var url = "/news"; 
    request.open("POST", url, true); 
    request.setRequestHeader("Content-Type", "application/json"); 
    request.send(mapTOJSON()); // perform the async POST 
} 

String mapTOJSON() { 
    print('mapping json...'); 
    var obj = new Map(); 
    obj['title'] = usrTitle.value == null ? "none" : usrTitle.value; 
    obj['description'] = usrDesc.value == null ? "none" : usrDesc.value; 
    obj['photo'] = usrPhoto.value == "none"; 
    obj['time'] = usrTime==null ? "none" : usrTime.value; 
    obj['ip']= '191.23.3.1'; 
    //obj["ip"] = usrTime==null? "none":usrTime; 
    print('sending json to server...'); 
    return Json.stringify(obj); // convert map to String i.e. JSON 
    //return obj; 
} 

我的服务器:

void serverInfo(HttpConnect connect) { 
    var request = connect.request; 
    var response = connect.response; 
    if(request.uri.path == '/news' && request.method == 'POST') { 
    response.addString('welcome from the server!'); 
    response.addString('Content Length: '); 
    response.addString(request.contentLength.toString()); 
    } else { 
    response.addString('Not found'); 
    response.statusCode = HttpStatus.NOT_FOUND; 
    } 
    connect.close(); 
} 

同样,我不希望浏览器要求从服务器的数据! 我在做什么是要求浏览器通过ajax提交JSON数据,而我只是不知道服务器(Rikulo Stream v0.5.5)如何获取数据的“内容”?所有代码均使用Google Dart Language M3编写。没有Javascript!

回答

1

Dart SDK不支持POST,但Dart团队计划对其进行增强。请给它加星标here: issue 2488。另一方面,由于你处理的是JSON,你可以听HttpRequest(我假设最新的SDK),并将List转换为String,然后转换为JSON。 Rikulo Commons提供了一个实用程序来简化作业,如下所示:

import "package:rikulo_commons/io.dart"; 

IOUtil.readAsJson(request, onError: connect.error).then((jsonValue) { 
    //handle it here 
}); 
相关问题