gpt4 book ai didi

ruby-on-rails - Ruby on Rails : send javascript array of arrays to ruby controller

转载 作者:行者123 更新时间:2023-12-04 05:34:28 24 4
gpt4 key购买 nike

我想将一个javascript数组数组发送到我的ruby Controller 。我有点迷茫。我的问题在 Controller 中。这是我到目前为止的内容:

(totalChanges是一个数组的数组。JSON.stringify(totalChanges)可能看起来像这样:

[[4,2,"","15"],[4,3,"","12"],[4,4,"","14"]]

app/views/index.html.erb:
<div id="dataTable" class="dataTable" style="width: 680px;height: 300px; overflow: scroll"></div>
<button>Save!</button>
<script>
var first = true;
var totalChanges = new Array();
$("#dataTable").handsontable({
//...some code that generates appropriate array totalChanges
});
var data = //..some code
$("#dataTable").handsontable("loadData", data);
$(function() {
$( "button").button();
$( "button" ).click(function() {
alert("clicked");
$.ajax({
type: "POST",
url: "/qtl_table/save",
data: {total_changes: JSON.stringify(totalChanges)},
success: function() { alert("Success!"); }
});
});
});

</script>

app/controllers/qtl_table_controller.rb:
def save
//Adding some things suggested by answers:
logger.debug "\n#{params[:total_changes].first}, #{params[:total_changes][1]}\n"
ar = JSON.parse(params[:total_changes])
end

我最终遇到这些错误:
NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.first):

编辑:我也有contentType:“应用程序/json”,并接受:“应用程序/json”,当我拿出那些都解决了。多谢你们 :)

最佳答案

JSON.parse 是您的 friend :

ar = JSON.parse(params[:total_changes])
#=> [[4, 2, "", "15"], [4, 3, "", "12"], [4, 4, "", "14"]]

您很可能需要将AJAX调用更新为以下内容:
$.ajax({
type: "POST",
url: "/qtl_table/save",
data: { total_changes: JSON.stringify(totalChanges) },
success: function() { alert("Success!"); }
});

给出您的数组参数 total_changes名称。

关于ruby-on-rails - Ruby on Rails : send javascript array of arrays to ruby controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11210366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com