如何将json数据从一个javascript函数传递到另一个javascript函数?

时间:2014-05-12 13:07:08

标签: javascript jquery ruby-on-rails-4

JS + Jquery + Rails 4

1。)view.html.erb

<%= select_tag "schedule[id]", options_for_select(@travel_names), {:multiple => true, :onchange => "renderSchedules(#{raw @schedule_hash.to_json},#{raw @deals_hash.to_json});" } %>

@schedule_hash = instance,  @deals_hash =实例  ,以json格式传递给js函数。

2。)webapp.js

function renderSchedules(json_data, deals_hash){
   new_json_data = filterSchedule(json_data, deals_hash);
   //More Code
}

function filterSchedule(json_data, deals_hash) {
//More Code
 $('#active_fiters_blk').append('<a href="#" id="active_travel_filter" style="color:#F26F21;margin-right:3%;" value="'+operator_ids[i]+'" onclick="removeTravelFilter('+json_data+','+deals_hash+')">"Link"</a>');
// Here i am getting json_data = [object Object], deal_hash = [object, Object] on console , i need to pass json data to removeTravelFilter function
}

function removeTravelFilter(jd, dh){
  //Some COnditions
  renderSchedules(jd, dh);
  // From here also i need to pass json data to renderSchedule function.
}

2 个答案:

答案 0 :(得分:0)

您需要对json_data进行字符串化,因为它是一个对象。 Object上的toString方法返回字符串"[object Object]"。你需要使用:

onclick="removeTravelFilter('+JSON.stringify(json_data)+','+JSON.stringify(deals_hash)+')">

答案 1 :(得分:0)

您最好不要使用内联脚本:

function filterSchedule(json_data, deals_hash) {
    $('<a href="#" id="active_travel_filter" style="color:#F26F21;margin-right:3%;" value="' + operator_ids[i] + '">Link</a>').on('click', function () {
        removeTravelFilter(json_data, deals_hash);
    }).appendTo('#active_fiters_blk');
}

据说,ID在文档上下文中必须是唯一的。您的代码看起来像是重复ID。