简体   繁体   中英

JavaScript array becomes Ruby Hash

Why do my array indices in JavaScript get sent to Ruby as strings? Instead of having scores[0], I access the first element as scores["0"]. I also access my instance vars not as score.candidate_id, but as score["candidate_id"]. How do I make this work?

Code: My JQuery sends scores via AJAX through this function:

$.post("submit.com", {scores: results}, function(data) {console.log(data)}, "json")

where results is an array consisting of

{judge_id: x, category_id: y, candidate_id: z, score: s}

Ruby Back-end (Sinatra and not working)

post '/submit' do

    woot = JSON.parse(params[:scores])

    woot.each do |new_score|
        Score.new({
            score: new_score["score"],
            pageant_id: Pageant.active.id,
            candidate_id: new_score["candidate_id"],
            judge_id: new_score["judge_id"],
            category_id: new_score["category_id"]
            }).save
    end

    params[:scores]["1"].inspect.to_json
end

Try to stringify your parameters before you sending it across. Try using firebug and see how the request is being sent with your current code. This basically happens because jQuery takes those keys in your JSON as names of form elements and it would consider it as though you have an element in your form.

Try sending it like this :

$.ajax({
 type : "POST",
 url :  'submit.com',
 dataType: 'json',
 contentType: 'application/json',
 data : JSON.stringify(results)
 });

In my app i don't use stringify though, but had encountered this issue once and used stringify to pass the data properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM