簡體   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