1
我嘗試了一些數據後從jQuery的web服務:語法問題,通過項目的數組中的Rails迭代
var jtvals={};
jtvals['line_items']=[];
var g={"name":"jon"};
var h={"name":"joan"};
jtvals['line_items'].push(g);
jtvals['line_items'].push(h);
$.ajax({
url: '/arc/v1/api/calculate_line_items',
type: 'POST',
data: jtvals,
dataType: 'json'
}).done(function(r){
alert('this is finished');
});
的Rails:
def calculate_line_items
line_items=params[:line_items]
puts line_items
puts line_items.count
puts "DO LOOP:"
line_items.each_with_index do |tmp_line_item, idx|
puts "idx:"
puts idx
puts "about to give you:"
puts tmp_line_item
puts "after giving you:"
和PARAMS是這樣的:
然而,它示數出有:
Parameters: {"line_items"=>{"0"=>{"name"=>"jon"}, "1"=>{"name"=>"joan"}}}
{"0"=>{"name"=>"jon"}, "1"=>{"name"=>"joan"}}
2
DO LOOP:
idx:
0
about to give you:
0
{"name"=>"jon"}
after giving you:
Completed 500 Internal Server Error in 2ms (ActiveRecord: 0.0ms)
TypeError (no implicit conversion of String into Integer):
app/controllers/api_orders_controller.rb:41:in `[]'
app/controllers/api_orders_controller.rb:41:in `block in calculate_line_items'
app/controllers/api_orders_controller.rb:33:in `each_with_index'
app/controllers/api_orders_controller.rb:33:in `calculate_line_items'
而我不知道爲什麼它把數組的鍵作爲輸出。我將如何解決這個問題?
奇怪,這是爲什麼?這是一個Rails的問題 - 我認爲它會直接排列。 – timpone
@timpone下面是我發現的一個(簡短)解釋:http://makandracards.com/makandra/27087-iterating-over-a-ruby-hash-and-while-tracking-the-loop-index。這是你想知道的嗎? – elements