html entities/escape for dynamic url (ajax updated url)?

独自空忆成欢 提交于 2019-12-12 02:29:13

问题


var fb_ps_page = window.location.href;
document.write('<iframe src="//www.facebook.com/plugins/like.php?href=' + fb_ps_page + '&amp;send=false&amp;layout=button_count&amp;width=450&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21&amp;appId=205223179497882" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:21px;" allowTransparency="true"></iframe>');

My function to write the dynamic url to facebook like button.

But, my url contains /, #, +, and & - do I need to escape these, and would I do that using regex?


回答1:


You are inserting into the URL context, so use proper URL encoding first:

document.write('<iframe src="//www.facebook.com/plugins/like.php?href=' + encodeURIComponent(fb_ps_page) + '&amp;send=false&amp;layout=button_count&amp;width=450&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21&amp;appId=205223179497882" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:21px;" allowTransparency="true"></iframe>');

As encodeURIComponent does already encode the HTML special chars ", &, and < (/, #, and + too), you don’t need need to encode it for the HTML context any more.



来源:https://stackoverflow.com/questions/9023983/html-entities-escape-for-dynamic-url-ajax-updated-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!