Pregunta

I'm using Thorax (Backbone + Handlebars) to develop an app, and am trying to load in an external JSON file that will be used in the template. Working with Coffeescript as well.

My test JSON data:

{
   "name" : "John Doe"
}

My template:

Thorax.templates['space'] = Handlebars.compile """
  <h2>Hello, {{name}}.</h2>
"""

The success function of my Ajax call:

success: (json) =>
    data = {space: json}
    $(app.appContainer).html(@template(data))

The entire process works up until actually displaying the data within the template. So all I get is Hello,. - I've tried following the instructions here and assigned the JSON data to an object, with no luck. And before you ask, I've console.log'ed json to check that the JSON data is in fact coming through.. it is.

Any suggestions?

¿Fue útil?

Solución

Saying @template(json) should work if json really is the { name: 'John Doe' } object. But it looks like you're getting a JSON string in your json argument rather than a parsed object. That would explain the results you're seeing from console.log, the output in your console looks more like what

console.log("{\n\"name\" : \"John Doe\"\n}")

would produce than what

console.log({"name": "John Doe"})

would produce.

Perhaps your server is sending back JSON with the wrong Content-Type so no knows that it is supposed to go through JSON.parse before your success handler is called. Try fixing your server code to include a Content-Type: application/json header; then you can say:

success: (json) =>
    $(app.appContainer).html(@template(json))

and it should work. If you can't do that then, as a last resort, you could parse the JSON yourself:

success: (json) =>
    json = JSON.parse(json)
    $(app.appContainer).html(@template(json))
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top