在backbonejs文档中,我们可以说我们可以在loading bootstrapped models下加载自举模型
所以我做了同样的事情
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请求来从服务器获取这些数据
由于
答案 0 :(得分:1)
Rails是对您的JSON进行HTML编码。有几种方法可以解决这个问题,但要注意使用像html_safe
这样的东西会产生安全隐患(XSS)。
How to Securely Bootstrap JSON in a Rails View很好地概述了安全执行此操作的一种方法(作者选择覆盖json_escape
)。
答案 1 :(得分:0)
您可能需要使用单引号"
替换所有"'"
,否则这不是有效的JavaScript。