【问题标题】:Unexpected token < in JSON at position 0 vuejs意外的令牌 < 在 JSON 中的位置 0 vuejs
【发布时间】:2018-10-17 11:24:03
【问题描述】:

我一直在寻找如何解决这个错误,但我不太了解如何解决它。

我在一个项目中使用 lottie-web,我必须在一个对象上设置动画的参数,以便稍后将其作为参数传递。

我的组件:

import Lottie from './../../node_modules/lottie-web/build/player/lottie';

export default {
  name: 'Illustration',
  mounted() {
    this.animationParams = {
      container: document.getElementById('animation'),
      renderer: 'svg',
      loop: 'true',
      autoplay: 'false',
      path: '/src/data/animation.json',
    };
    Lottie.loadAnimation(this.animationParams);
  },
  data() {
    return {
      animationParams: {
      },
    };
  },

但是当这一行被执行时:

    Lottie.loadAnimation(this.animationParams);

我得到这个错误:

Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.xhr.onreadystatechange

我在 Stackoverflow 的其他答案中看到的是,我不必解析 json,因为它已经被解析了,但我不知道如何不解析它。

这是 json 文件中的内容:http://myjson.com/s0kn6。

如何在不解析的情况下加载该 json 文件?

【问题讨论】:

  • 查看浏览器开发工具的网络选项卡。您可能没有得到 json,而是 html。
  • 好吧,我查过了,但事实并非如此:/
  • @CarlosPisarello 您的服务器上可能找不到指定的路径(/src/data/animation.json),可能设置为重定向到 404 页面(即 HTML),无法解析为 JSON .我会在 DevTools 中仔细检查该路径的相应网络响应。
  • 您是否可以分享来自 chrome 开发者工具的网络调用的屏幕截图以及该网络调用的响应? @tony19 的评论在这一点上是有道理的。
  • 当然! @highhope 这里是:ibb.co/drGVM7 文件是 Cuentas.json(在帖子中我将其更改为 animation.json 以更好地理解问题)

标签: javascript json parsing vue.js lottie


【解决方案1】:

您的服务器不太可能在为 /src/data/animation.json 提供服务。而不是使用path 使用animationData 并直接设置动画对象(而不是通过服务器调用)。

首先,我只需将动画数据设置为导出对象而不是 json 的常规 ES6 模块。

/src/data/animation.js

export default {
  // your animation data
}

请注意,这是一个 javascript 文件,而不是 json 文件。然后在您的组件中,只需导入该对象。

import Lottie from './../../node_modules/lottie-web/build/player/lottie';
import animationData from "/src/data/animation"

export default {
  name: 'Illustration',
  mounted() {
    this.animationParams = {
      container: document.getElementById('animation'),
      renderer: 'svg',
      loop: 'true',
      autoplay: 'false',
      animationData,
    };
    Lottie.loadAnimation(this.animationParams);
  },
  data() {
    return {
      animationParams: {
      },
    };
  },

这已记录在here。

这将使您的初始捆绑包更大,但您无需额外调用服务器以获取动画数据。

除此之外,您需要将 animation.json 移动到您的服务器正在服务的某个路径,并将 path 设置为相对于当前加载的页面的 URL。

【讨论】:

    猜你喜欢
    • 2016-12-13
    • 1970-01-01
    • 2020-02-05
    • 2021-09-12
    相关资源
    最近更新 更多