私はレールアプリに取り組んでおり、AJAX リクエストを介してコントローラーに渡す動的な量の変数を作成したいと考えています。つまり、オブジェクトが 3 つしかない場合は 3 つの変数を作成し、オブジェクトが 5 つある場合は 5 つの変数を作成します。
私の JavaScript ファイルでは、動的な量の変数を作成することができました。
var count = parseInt("#{@matches.count}");
while(count>0){
eval("result_" + count + "= $('input:radio[name=result_" + count + "]:checked').val()");
count -= 1;
}
これによりresult_1
、result_2
、result_3
、 などが作成されます。
これまでの AJAX リクエストは静的で、常に 5 つの結果が必要です。これをダイナミックにしたい。
$.ajax({
type: 'GET',
url: '/mt_results/create',
dataType: 'json',
data: {
'result_1' : { matched_id: "#{@matches.first.id}", result: result_1 },
'result_2' : { matched_id: "#{@matches.second.id}", result: result_2 },
'result_3' : { matched_id: "#{@matches.third.id}", result: result_3 },
'result_4' : { matched_id: "#{@matches.fourth.id}", result: result_4 },
'result_5' : { matched_id: "#{@matches.fifth.id}", result: result_5 }
},
success: function(e){
console.log("AWWWWWWW YEAH!!");
}
});
これにアプローチして動的に JSON オブジェクトを作成し (私が作成した方法と同様results_#
)、それを変数に割り当てます (それを と呼びましょうdata_var
)。次に、以下のように data_var を渡すだけです。
data: data_var
コードを改善する方法に関するヒントやフィードバックをいただければ幸いです。