在我喜欢的模型
中,
def question_hash_string
@question_hash_string || '{}'
end
def question_hash
ActiveSupport::JSON.decode question_hash_string
end
在 Javascript
中,
var question_hash_element = document.getElementById('enr_rds_batch_update_question_hash_string');
var question_hash = JSON.parse(question_hash_element.value);
question_hash[batch_question_id] = (batch_answer_id || batch_rdsap_answer || batch_answer_checkbox);
question_hash_element.value = JSON.stringify(question_hash);
它会给出类似 "{"16":"3","28":false}"的值
我想添加另一个值,其答案如下,
question_hash[batch_question_id] = ((batch_answer_id || batch_rdsap_answer || batch_answer_checkbox) && (build_id));
"{"16":"3","28":false:"2", "3":"55":"54"}"
等等。我需要使用带有“:”的现有记录添加另一列。
最佳答案
向 JavaScript 对象添加键/值对:
var question_hash = { question_id:2, answer_id:3 };
question_hash.build_id = 6;
关于javascript - 如何在 ruby on Rails 和 Javascript 中向现有 JSON 对象添加另一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14336963/