从 javascript/jquery 到 ruby/sinatra 的多维数组
请问如何将二维数组从 javascript 传递到 ruby?我在客户端有这个:
function send_data() {
var testdata = {
"1": {
"name": "client_1",
"note": "bigboy"
},
"2": {
"name": "client_2",
"note": "smallboy"
}
}
console.log(testdata);
$.ajax({
type: 'POST',
url: 'test',
dataType: 'json',
data: testdata
});
}
在服务器端有这个:
post '/test' do p params end
但我无法正确处理。我在服务器端能得到的最好的结果就是
{"1"=>"[object Object]", "2"=>"[object Object]"}
我尝试在客户端添加 JSON.stringify 并在服务器端添加 JSON.parse ,但第一个结果是
{"{\"1\":{\"name\":\"client_1\",\"note\":\"bigboy\"},\"2\":{\"name\":\"client_2\",\"note\":\"smallboy\"}}"=>nil}
后者抛出 TypeError - 无法将哈希转换为字符串。
任何人都可以帮忙,或者发布一小段正确的代码吗?谢谢
how do I pass a 2-dimensional array from javascript to ruby, please? I have this on client side:
function send_data() {
var testdata = {
"1": {
"name": "client_1",
"note": "bigboy"
},
"2": {
"name": "client_2",
"note": "smallboy"
}
}
console.log(testdata);
$.ajax({
type: 'POST',
url: 'test',
dataType: 'json',
data: testdata
});
}
and this on server side:
post '/test' do p params end
but I can't get it right. The best I could get on server side is something like
{"1"=>"[object Object]", "2"=>"[object Object]"}
I tried to add JSON.stringify on client side and JSON.parse on server side, but the first resulted in
{"{\"1\":{\"name\":\"client_1\",\"note\":\"bigboy\"},\"2\":{\"name\":\"client_2\",\"note\":\"smallboy\"}}"=>nil}
while the latter has thrown a TypeError - can't convert Hash into String.
Could anyone help, or maybe post a short snippet of correct code, please? Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能需要在 javascript 端手动构建 JSON:
这将构建一个包含对象的数组。
它可能看起来像这样:
我这里可能有一些东西,但这应该接近它的样子。
You may want to build up the JSON manually, on the javascript side:
This will build an array of arrays with objects.
It may look like this:
I may have something off here, but this should be close to what it would look like.
我不确定这是否有帮助,但我有两个想法:序列化字段和/或迭代数组。
我设法通过设置序列化必须存储子数组的字段来将json数组放入activerecord对象中:
并使用迭代器来处理json数组:
来回转换似乎有点麻烦,但我发现它是最重要的处理数组的明显方法。
I'm not sure if this will help but I've got two thoughts: serialize fields and/ or iterate the array.
I managed to get a json array into activerecord objects by setting serializing the fields which had to store sub-arrays:
and using an iterator to process the json array:
The conversion back-and-forth seems a bit cumbersome but I found it the most obvious way to handle the array.