在backbonej文档中,有人说我们可以在加载自举模型的情况下加载自举的模型
所以我和一样
employeeCollection.reset(<%= @employees.to_json %>);
但我抛出了一个错误
Uncaught SyntaxError: Unexpected token &
当我点击那个错误时,它把我带到了
employeeCollection.reset([{"address":"Madhyapur thimi 13, wamunae tole","fired":false,"first_name":"Gagan Shrestha","id":1,"last_name":"Shrestha","phone":"9841971919"},{"address":"Madhyapur thimi 13, wamunae tole","fired":true,"first_name":"Prem Krishna","id":2,"last_name":"Shrestha","phone":"9841755640"},{"address":"sdgd","fired":false,"first_name":"fdsfs","id":3,"last_name":"sfdsf","phone":"5345435"},{"address":"sdfsf","fired":true,"first_name":"dsfsd","id":4,"last_name":"fsd","phone":"sfdsf"},{"address":"Madhyapur thimi 13, wamunae tole","fired":false,"first_name":"Prafulla","id":5,"last_name":"Shrestha","phone":"9841971919"},{"address":"South africa","fired":false,"first_name":"ram","id":6,"last_name":"krishna","phone":"86879979"},{"address":"sdfdsf","fired":true,"first_name":"fs","id":7,"last_name":"sdfdsfdsf","phone":"sdfdsfds"},{"address":"juj","fired":true,"first_name":"rfr","id":8,"last_name":"hgtg","phone":"9898"},{"address":"gthy","fired":true,"first_name":"olo","id":9,"last_name":"plo","phone":"6766"},{"address":"rfrf","fired":true,"first_name":"uyuy","id":10,"last_name":"uyuy","phone":"7676"},{"address":"madhyapur thimi 12","fired":true,"first_name":"shuvam1","id":11,"last_name":"shrestha","phone":"1234556778"},{"address":"dodale","fired":true,"first_name":"sarita2","id":12,"last_name":"prajapati","phone":"985757"},{"address":"kathmandu","fired":false,"first_name":"hello","id":13,"last_name":"world","phone":"0155675432"}]);
我想这个错误是由于json数据的转义,但不太确定。
我需要做额外的事情吗?这样我就可以在页面加载时加载必要的数据,这样我就不需要触发ajax请求来从服务器获取这些数据
感谢
Rails是对JSON进行HTML编码的。有几种方法可以解决这个问题,但要注意,仅仅使用html_safe
之类的东西会带来安全隐患(XSS)。
如何在Rails视图中安全地引导JSON提供了一种安全的方法(作者选择覆盖json_escape
)。
您可能需要用一个单引号"'"
替换所有"
,否则这是无效的javascript。