繁体   English   中英

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

[英]How to pass json data from one javascript function to another javascript function?

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 =实例,@deals_hash = instance,以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.
}

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

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

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

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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