我要求浏览器使用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!
答案 0 :(得分:1)
另一方面,由于您处理的是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
});