string的Javascript数组转换为对象数组
我从服务器发送string数组:
Node.JS + Express.JS
app.get('/url', function (req, res) { res.send(["item1", "item2", "item3"]); })
但是在前端,我收到了一些对象:
Angular.JS
SomeResource.query(function (data) { console.log(data); });
在控制台中
0: Resource 0: "i" 1: "t" 2: "e" 3: "m" 4: "1" $$hashKey: "008" __proto__: Resource 1: Resource 0: "i" 1: "t" 2: "e" 3: "m" 4: "2" $$hashKey: "009" __proto__: Resource 2: Resource 0: "i" 1: "t" 2: "e" 3: "m" 4: "3" $$hashKey: "00A" __proto__: Resource
为什么发生这种情况? 我怎样才能在前端接收相同的数组? 谢谢
这是因为不幸的是, MIME不支持JavaScript Arraytypes的数据。
由MIME标准定义的内容types在电子邮件之外也是重要的,例如像万维网的HTTP之类的通信协议。 HTTP要求数据在类似电子邮件的消息的上下文中传输,尽pipe数据通常不是实际的电子邮件。
使用JSON。
您可以在浏览器debugging器控制台(如Firebug)或节点控制台上进行确认。
var json = JSON.stringify(["item1", "item2", "item3"]); ->undefined JSON.parse(json); ->["item1", "item2", "item3"]
所以,在服务器端
app.get('/url', function (req, res) { res.send(JSON.stringify(["item1", "item2", "item3"])); })
和JSON.parse
数据在客户端获取数组。