我正在使用remotipart使用ajax上传和升级图像,问题是当我编辑项目时,ajax更新了数据,但是remotipart(https://github.com/leppert/remotipart)返回图像的“解析错误”更新。

这是我的表格的样子:

= form_for(Achievement.new), html: {multipart: true , remote: true} do |f|
          = f.text_field :name
          = f.text_area :description
          = f.file_field :image
          = f.submit 'Send'


我正在使用一个表单来创建,编辑和删除“成就”。这是我的js:

constructor: ->
    $('.edit_button').click ->
      $.ajaxSettings.dataType = "json"
      @id = $(this).data('id')
      @content = $(this).parent()
      @name = $('.form_achievement #name')
      @description = $('.form_achievement #description')
      @image = $('.form_achievement .avatar img')
      @button = $('.form_achievement form input:submit')
      @form = $('.form_achievement form')

      #Load data to edit on form
      $.ajax
        type: 'get'
        url: "/en/private/achievements/#{@id}/edit/"

        success: (data) =>
          alert 'edit'
          @name.val(data.achievement.name)
          @description.val(data.achievement.description)
          @stat.html(data.achievement.stat)
          @value.val(data.achievement.value)
          @image.prop 'src', data.image

        #Change method of the form to put and bind event
        $.ajaxSettings.dataType = "json"
        @form.attr('method','put')
        $('.form_achievement form').attr('action', "/en/private/achievements/#{@id}")
        $('#achievement_form.accordion .form_achievement').unbind('click', NewAchievement)

        @form.bind 'ajax:success', (xhr, data, status) =>
          @content.slideUp 'slow', ->
            $(this).remove()
          alert 'Edit'

        @form.bind 'ajax:error', (event, response, error) =>
          alert error
        @button.bind 'change', => @changeButton()


        error: (data) ->
          alert 'error'

  changeButton: ->
    @form.submit()


当我尝试进行不更改图像的编辑时,这解决了我的问题,但是当我尝试进行升级到新图像的编辑时,返回“解析错误”。谁能帮我?

最佳答案

您很可能会收到解析错误,因为您的响应实际上是HTML。

问题是默认情况下,remotipart假定服务器响应为JS。您可以在呈现表单时设置数据类型,具体情况如下:

form_for(Achievement.new), html: {:'data-type' => :html, :multipart => true, :remote => true}


或者可以像这样在JS中完成:

@form.bind 'ajax:remotipartSubmit', (event, xhr, settings) =>
    settings.dataType = "html *"

关于ruby-on-rails - 使用Remotipart解析错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14508260/

10-12 13:46