我想从node.js向浏览器javascript发送一组对象。我猜它的方式是序列化它,通过response.write发送,然后在浏览器端反序列化。我猜对了吗?没有使用包的任何其他方式?问题是如何实现它,在服务器上序列化和在浏览器上反序列化?
答案 0 :(得分:1)
是的,你是对的,这就是JSON所生的。您可以在服务器上使用JSON.stringify
对其进行序列化,并在客户端使用JSON.parse
对其进行反序列化。
var array = [{ id: 4, text: "Hello four" }, { id: 9, text: "Hello nine" }];
res.end(JSON.stringify(array));
在客户端,例如:
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", '/routeServingTheObject', false);
xmlHttp.send(null);
var object = JSON.parse(xmlHttp.responseText);
这不使用任何公共库,例如jQuery。请注意,JSON不支持诸如函数之类的东西。需要将javascript脚本发送到客户端而不是JSON。然而,为了完成任何复杂的任务,我会建议你使用某种形式的模板系统或库socket.io,这通常是一种更好的方式来做事,至少如果你没有大量的时间创建自己的工具。
答案 1 :(得分:0)
这个简单的脚本演示了这个概念。它完美地运作:
var body = '<!DOCTYPE html>'+
'<html lang="en">'+
'<head>'+
'<meta charset="UTF-8">'+
'<title>lab</title>'+
'</head>'+
'<body>'+
'<script>%SCRIPT%</script>'+
'</body>'+
'</html>';
// array foo is defined in node.js server
var foo = [];
foo[0] = 'hello';
foo[1] = 'world';
// or it can be defined as bellow
foo = [{id: 4, text: "Hello four"}, {id: 9, text: "Hello nine"}];
// array foo is passed to client browser
var str = '';
str += 'var obj = '+JSON.stringify(foo)+';';
str += 'console.log(obj);';
body = body.replace('%SCRIPT%', str);
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(body);