2

我正在通过添加自定义模块来扩展 aurelia 的入门应用程序。读取 json 时出现错误“Uncaught SyntaxError: Unexpected token :”。但是 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 的复制粘贴,可以在示例代码中找到)` import {inject} from '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() 中。这是唯一的区别。这可能是我问题的根源吗?

4

1 回答 1

6

是的,这就是你问题的根源。jsonp当你真的不需要它时,你正在使用它。由于您自己提供静态 json 文件,并且可能在主应用程序所在的同一域上提供服务,因此您不需要使用 jsonp。如果您还不熟悉,那么这里有关于 jsonp 的很好的解释(flicker 将响应包装在函数调用中,因为 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;
});
于 2015-04-28T21:49:21.783 回答