简体   繁体   中英

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 = instance, @deals_hash = instance , passing to the js function as json format.

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.
}

You need to stringify your json_data because it is an Object. The toString method on an Object returns the string "[object Object]" . You need to use:

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

You'd have better to not use inline script:

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');
}

That's said, IDs must be unique on document context. Looks like your code is duplicating IDs.

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