我是新來的rails。我正在嘗試使用ajax並調用控制器方法。控制器方法創建了一個實例變量,我認爲這個變量可以在ajax中成功回調。將導軌變量傳遞給javascript中的ajax
但是,每當我運行代碼時,JS控制檯都會給出「test_array爲null」錯誤。請提出解決方案並瞭解正在發生的事情。代碼如下。
我已經在互聯網上徹底研究過這個問題(包括SO),但沒有一個答案似乎適合我的問題。
sentiscores_controller.rb
def render_phrase
@tag_cloud_temp = [{text: 'Hello', weight: 1000},{text: 'World!', weight: 1100}]
end
index.html.erb
$.ajax({
type: 'GET',
url: '/sentiscores/render_phrase',
data: {'senti_score': 5},
success: function(){
var test_array = <%= raw @tag_cloud_temp.to_json%>;
console.log(test_array[0]['text']);
},
error: function(exception){
console.log("Error! : "+exception);
}
})
實際的HTML源代碼如下所示
$.ajax({
type: 'GET',
url: '/sentiscores/render_phrase',
data: {'senti_score': 5},
success: function(){
var test_array = null;
console.log(test_array[0]['text']);
},
error: function(exception){console.log("Error! : "+exception);}
})
如果您只記錄完整陣列,輸出是什麼? 'console.log(test_array)' – jon1467
實際生成的JavaScript代碼是什麼樣的? – David
@ jon1467如果我記錄它給出的完整數組 - null在JS控制檯上。 – AndEnthu