Rails 為什麼要使用 escape_javascript?

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
641   0  
·
2018/07/31
·
3 mins read


在 Rails 中,我們很常用到 javascript,通常不管是用 jQuery 或是其他的 ajax call,透過 routes.rb 中指定的 controller action,它就會去執行對應的 action_name.js.erb,我想這沒有太大的問題,但是如果有時候寫得太快,寫得太順,就會想說,反正 action_name.js.erb 最後會以 javascript 執行,javascript 也天天寫,結果就是,不動了,而且很特別的是,你很難找到問題在那裡!

一般就是忘了用:escape_javascript( ) 或是 j( )

我們先來看看這 escape_javascript 或是 j 到底做什麼?

文件上寫得很簡單:Escapes carriage returns and single and double quotes,也就是將回車字元及單雙引號跳脫,其實看一下程式碼就很容易懂了:

  • '\\' => '\\\\',
  • "</" => '<\/',
  • "\r\n" => '\n',
  • "\n" => '\n',
  • "\r" => '\n',
  • '"' => '\\"',
  • "'" => "\\'"

哈,就是將以上這些字元轉換,所以它做的事,如以下這個常用的 javascript 來說:

$('#target_id').html('<%= j render 'partial_123' %>');

不過就是將 partial_123 render 後,再將一些字元轉換掉,但是不執行這,為什麼就會程式不動,而且很難抓問題?

原因就在 javascript 的語法不對

在 javascript 中,雙引號字串是參數,斜線 (/)是 regular expression,如果 partial_123 render 後,含有這些字元,而不將這些字元換掉,那就不是一個合法的 javascript 語言了,現在懂了吧!

而且,瀏覽器中看不到錯的地方

寫得太快,忘了寫 escape_javascript( ) 或是 j( ) 是常常發生的,而且有時還真不會錯,因為只要原始的內容剛好沒有這些要跳脫的字元,就不會錯,但是如果是動態內容,或是本身就是有要跳脫的字元,就會很頭大,一般都不會想到是忘了寫 escape_javascript( ) ,直接到瀏覽器中查看 server 回應是最直覺的除錯方式,往往怎麼看,怎麼試都查不到錯誤點,因為瀏覽器中會直接把換行迴車等字元執行,也就是,會看到換行,但是看不到 \r\n,看到 </ ,會直覺不過就是一個很正常的結束html tag,這些都很難看出錯誤,而且,瀏覽器也不會顯示錯誤,javascript 會把這些錯誤吞下去不執行,這,真是很討厭。

javascript 不動時,先看看是不是漏了 j( )

會寫這篇,當然是我也遇到同樣的問題,寫了當紀念,也希望也機會看到的 Rails 愛好者,下次遇到 javascript 不動時,先看看是不是漏了 j( ) 。


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

分類於:
標籤:
日期:
創作於:2018/07/31,最後更新於:2018/07/31。
合計:645字


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.