2013-03-23 92 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 
}); 
相關問題