【问题标题】:How to show nested array of json in html in ember.js如何在ember.js中的html中显示嵌套的json数组
【发布时间】:2014-11-12 23:33:17
【问题描述】:

我试图在 html 中显示我在 app.js 中收到的 json,但它不起作用。有什么想法吗?

app.js 的代码(我确定 $.post 返回一个有效的 json)

App.CadeirasRoute = App.AuthenticatedRoute.extend({
  model: function() {
    alert(this.getUsername());
     $.post('/api/database/cadeira/', {"token": this.postJSONWithToken()}).then(function(response) {
        if (response.success) {
            alert(response.results[0].codigo); // this alerts right on browser with the right value of codigo of the first json in the array

            return response.results;
        }
     });
  }
});

我的 html 代码

<script type="text/x-handlebars" id="cadeiras">
    <div id="cadeiras">
        {{#each item in model}}
      <h2>{{item.codigo}}</h2>
    {{/each}}
    </div>
  </script>

【问题讨论】:

  • 你能贴出 JSON 响应的代码吗?

标签: jquery html ajax json ember.js


【解决方案1】:

“模型”属性应该返回一个承诺

relevant api entry

你目前没有返回任何东西

这可以通过简单地在这一行添加'return'来解决

 return $.post('/api/database/cadeira/', {"token": this.postJSONWithToken()}).then(function(response) {

虽然我认为我更好的解决方案是返回 Ember 承诺

App.CadeirasRoute = App.AuthenticatedRoute.extend({
  model: function() {
    alert(this.getUsername());
    //create promise to be returned as per Ember api requirements
    return new Ember.RSVP.Promise(function(resolve, reject) {
        //submit ajax request similar to your previous one
        Ember.$.ajax({ 
            url: '/api/database/cadeira/',
            dataType: 'json',
            type: 'POST',
            data: {"token": this.postJSONWithToken()}),
            contentType: 'application/json'
        }).then(function(response) { //this handles a successful response
            alert(response.results[0].codigo);
            resolve(response.results);
        }, function(xhr) { //this handles a failed response
            var response = JSON.parse(xhr.responseText);
            Ember.run(function() {
                reject(response.error);
            });
        });
     });
  }
});

传入'.then()'的第一个函数是成功时发生的事情,第二个是失败时发生的事情。 resolve(value) 通过 promise 传递成功,在这种情况下,允许将模型设置为“已解决”的值。

其他可能有用的链接

Ember.RSVP.Promise

(带有承诺的自定义令牌身份验证器的一个很好的例子)

Ember Simple Auth custom server example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 2019-10-24
    • 1970-01-01
    • 2021-11-08
    • 2015-07-12
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多