bde*_*vic 3 json ruby-on-rails handsontable
我想将一个javascript数组数组发送到我的ruby控制器.我有点迷茫.我的问题出在控制器中.这是我到目前为止:
(totalChanges是一个数组数组.JSON.stringify(totalChanges)可能如下所示:
[[4,2,"","15"],[4,3,"","12"],[4,4,"","14"]]
Run Code Online (Sandbox Code Playgroud)
应用程序/视图/ 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>
Run Code Online (Sandbox Code Playgroud)
应用程序/控制器/ 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
Run Code Online (Sandbox Code Playgroud)
我最终得到了这些错误:
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):
Run Code Online (Sandbox Code Playgroud)
编辑:我也有contentType:"application/json",接受:"application/json",当我拿出那些东西时,一切都解决了.多谢你们 :)
KL-*_*L-7 10
JSON.parse 是你的朋友:
ar = JSON.parse(params[:total_changes])
#=> [[4, 2, "", "15"], [4, 3, "", "12"], [4, 4, "", "14"]]
Run Code Online (Sandbox Code Playgroud)
您很可能需要将AJAX调用更新为:
$.ajax({
type: "POST",
url: "/qtl_table/save",
data: { total_changes: JSON.stringify(totalChanges) },
success: function() { alert("Success!"); }
});
Run Code Online (Sandbox Code Playgroud)
给出你的数组参数total_changes名称.
| 归档时间: |
|
| 查看次数: |
8347 次 |
| 最近记录: |