【问题标题】:Rails + Vue Unexpected token u in JSON at position 0Rails + Vue 位置 0 处 JSON 中的意外标记 u
【发布时间】:2019-11-21 18:28:04
【问题描述】:

尽管 rails 6 仍处于测试阶段,但我想测试它来构建一个 rails + vue 应用程序,但是当尝试解析 json 数据时,我在控制台中遇到错误“VM353:1 Uncaught SyntaxError: Unexpected token u in JSON在位置 0" 不知道为什么我的数据没有被解析。未定义但不知道为什么

这是我的 hello_vue.js 文件

import Vue from 'vue/dist/vue.esm'
import VueResource from 'vue-resource'

Vue.use(VueResource)



     document.addEventListener('DOMContentLoaded', () => {
          Vue.http.headers.common['X-CSRF-Token'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content')

          var element = document.getElementById("gameapp-form") 
          if(element != null) {

              var game_application = JSON.parse(element.dataset.game_application)

              var app = new Vue({
                el: element,
                data: function () {
                    return { game_application: game_application}
                }, 
                methods: {
                    saveApplication: function() {
                        this.$http.post('/game_applications', {game_application: this.game_application }).then(response => {
                            console.log(response)
                        }, response => {
                            console.log(response)
                        })
                    }
                }
              })

            }
        }

    )

这是我的 _form.html.erb 文件

<%= content_tag :div,
  id: "gameapp-form",
  data: {
    game_application: game_application.to_json(except: [:created_at, :updated_at]),
  } do %>

  <label>Game Name</label>
  <input type="text" v-model="game_application.name" />

  <label>Game Name</label>
  <input type="text" v-model="game_application.video_link" />

  <button v-on:click="saveApplication">Send Application</button>
<% end %>

【问题讨论】:

    标签: ruby-on-rails vue.js


    【解决方案1】:

    在您的 axios 请求中使用 response.data

    this.$http.post('/game_applications', {game_application: this.game_application})
              .then(response => response.data)
              .then(response => {
                console.log(response)
              })
    

    Axios 在 data 字段中返回您的 JSON 输出。所以,在第一个then 中,我们基本上返回response.data,以便您可以在下一个then 中使用它。希望这是有道理的。

    【讨论】:

      猜你喜欢
      • 2016-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      • 2018-01-29
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      相关资源
      最近更新 更多