3

我要求浏览器使用 ajax 将 JSON 数据 POST 到流 v0.5.5 服务器。在服务器端,如何接收来自 ajax 请求的数据?

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

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!

4

1 回答 1

1

Dart SDK 中不支持 POST,但 Dart 团队计划对其进行增强。请在这里观星: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
});
于 2013-03-25T01:44:46.730 回答