【问题标题】:Json parseerror & unexpected tokenJson parseerror & 意外令牌
【发布时间】:2016-04-12 14:06:01
【问题描述】:

仍在尝试修复我的 ajax 以使用控制器。 现在我收到此错误消息:

response SyntaxError: Unexpected token j ,  xhr[object Object] ,  STATUS parsererror

config.routes

resources :books do 
    member do 
      get '/last_chapter/', to: 'chapters#last_chapter', as: 'last_chapter', defaults: { format: 'json' }
    end
    resources :chapters
  end 

章节控制器

def last_chapter
        @last_chapter = Chapter.order(created_at: :desc).limit(1)
        respond_to do |format|
            format.json
        end
    end

last_chapter.json

json.extract! @last_chapter, :id, :title, :characters, :created_at, :updated_at

脚本.js

$.ajax({
      type: "GET",
      url: '/books/103/last_chapter.json',
      contentType: "application/json",
      success: function(data) {
        console.log('JAAAA ENDELIG FUNKER DET');
        $("body").html(data);
      },
      error: function(xhr, status, response) {
        console.log('response ' + response +  ' ,  xhr' + xhr +  ' ,  ' + 'STATUS ' + status)}
    });

感觉我已经尝试了一切。如果您需要更多信息,请告诉我! :)

【问题讨论】:

    标签: ruby-on-rails json ajax


    【解决方案1】:

    我认为您的问题在于路线。这是我会做的:

    resources :books do
      get :last_chapter, on: :member
    end
    

    books_controller.rb

    def last_chapter
      @last_chapter = Book.find(params[:id]).chapters.last
      respond_to do |format|
        format.json do
          render json: { does_it_work: :yes }
        end
      end
    end
    

    我假设以下模型:

    class Book < ActiveRecord::Base
        has_many :chapters
    end
    

    【讨论】:

    • 你会如何做 ajax 的 url?现在它找不到“/last_chapter”,因为我需要最后一章的 ID。
    • 我会保留 ajax 调用。 last_chapter 操作有什么意义,那么如果您需要知道它的 id 呢?您需要提供book_id,然后此操作应返回本书的最后一章!
    • 另外,当我像这样手动添加 url(带有章节 ID)时。 url:'/books/103/chapters/206/last_player.json',我收到此错误:`响应 storage.get 时出错:TypeError:无法在 Object.callback 处读取 null 的属性“样式”(chrome 扩展: //kchdfagjljmhgapoonapmfngpadcjkhk/js/scripts.js:24:42) 在 chrome-extension://kchdfagjljmhgapoonapmfngpadcjkhk/js/scripts.js:11:21`
    • 如果我保留 url 原样,它会给我这个错误:404 (Not Found)
    • 你有id为103的书吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 2014-10-13
    • 2012-09-21
    • 1970-01-01
    相关资源
    最近更新 更多