2014-12-24 37 views
0

我需要幫助在application.html.erb佈局文件的腳本標記中顯示rails helper方法的輸出。 我把下面的代碼在結束HTML標記之前:Ruby on Rails在應用程序中嵌入Ruby代碼Erb文件

<script> 
    App.ready = function() { 
     App.initApp(jQuery.parseJSON("<%= current_user_json %>")); 
    } 
</script> 

這current_user_json是一個輔助方法,它是在應用程序控制器文件。

上面的代碼產生在瀏覽器(查看頁面源)的輸出是:

<script> 
    App.ready = function() { 
     App.initApp(jQuery.parseJSON("{&quot;id&quot;:3,&quot;email&quot;:&quot;[email protected]&quot;,&quot;username&quot;:null}")); 
    } 
</script> 

正確的輸出應該是:

<script> 
    App.ready = function() { 
     App.initApp(jQuery.parseJSON('{"id":3,"email":"[email protected]","username":null}')) 
    } 
</script> 

如果有人可以幫助我,我真的會解決這個問題我想在過去幾天解決。

+1

不'<%= current_user_json.html_safe%>'工作? – spickermann

+0

嗨@spickermann您的回答是正確的! – codingbear

回答

1

更改此:

<%= current_user_json %> 

要這樣:

<%= current_user_json.html_safe %> 

擡起頭,你必須確保你的JSON是正確轉義。例如,如果您的current_user_json恰好有一個帶有引號的字段,則必須轉義該引號。如果你沒有逃脫,那麼你正在做的是一個非常典型的黑客攻擊媒介,所以要謹慎行事。

+0

您好@joelparkerhenderson,感謝您的快速,有用和準確的反應。我不太熟悉'攻擊媒介'。你能幫我指點一些在線的資源,我可以閱讀和了解更多關於它們的資料,以保護它的代碼。 – codingbear

+0

不客氣。要了解更多有關攻擊媒介的信息,關鍵的想法是您要混合不同類型的字符串,而某些字符可能有特殊的含義會干擾某些字符串。谷歌的「跨網站請求僞造」,你會看到很多例子。 – joelparkerhenderson

2

試試這個

<%= raw current_user_json.to_json %> 
+0

Hi @ pkrawat1感謝您的驚人迴應,如果輔助方法未設置爲輸出json,您的答案將是正確的。所以歡呼,並再次感謝。 – codingbear