我想向我的 ruby 控制器发送一个 javascript 数组。我有点失落。我的问题在控制器中。这是我到目前为止所拥有的:
(totalChanges 是一个数组数组。JSON.stringify(totalChanges) 可能如下所示:
[[4,2,"","15"],[4,3,"","12"],[4,4,"","14"]]
应用程序/视图/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>
应用程序/控制器/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:“application/json”和 Accepts:“application/json”,当我把它们拿出来时,一切都解决了。多谢你们 :)