在Aurelia.io示例中读取json时出错

时间:2015-04-28 21:05:53

标签: javascript json jsonp aurelia

我通过添加自定义模块来扩展aurelia' get started app。 我收到错误" Uncaught SyntaxError:意外的令牌:"一边读一个json。但是json验证器没有发现任何错误。

这是我的json { "news": [ { "title": "Lorem Ipsum is simply dummy text", "type": "news", "tags": [ "news", "fish", "loremipsumdolor" ], "text": "Lorem Ipsum is simply dummy text of the printing and typesetting industry." }, { "title": "Lorem Ipsum", "type": "news", "tags": [ "news", "fish" ], "text": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s." } ] }

这是我的模块试图加载json(基本上它是来自flickr.js的复制粘贴,可以在示例代码中找到) `     从&aurelia-framework'中导入{注入};     从&aurelia-http-client';

导入{HttpClient}
@inject(HttpClient)
export class News{
  heading = 'News';
  items = [];
  url = '/res/data.json';

  constructor(http){
    this.http = http;
  }

  activate(){
    debugger;
    return this.http.jsonp(this.url).then(response => {
      this.items = response.content.news;
    });
  }

  canDeactivate(){
    return confirm('Are you sure you want to leave?');
  }
}

' 当执行示例代码时,它从flikr加载json并将其包装在jsonp_callback_92661()中。这是唯一的区别。可能它是我问题的根源吗?

1 个答案:

答案 0 :(得分:6)

是的,那是你问题的根源。当您不需要时,您正在使用jsonp。由于您自己提供静态json文件,并且可能在主应用程序所在的域中提供服务,因此您不需要使用jsonp。如果您还不熟悉,Good explanations about jsonp就在这里(闪烁包含函数调用中的响应,因为jsonp需要这样做)。

您应该可以使用get

return this.http.get(this.url).then(response => {
  //not sure if response.content is an object already.
  //you may need to JSON.parse response.content
  this.items = response.content.news;
});