【问题标题】:Rails respond_to issue with jsonRails respond_to 问题与 json
【发布时间】:2012-07-12 03:55:29
【问题描述】:

我正在上传一些 HTML5,但遇到了一个我似乎无法弄清楚的问题。拿这个功能代码:

if @image.save
    render :json => {:status => "Successfully uploaded image!"}
else
    render :json => {:status => "Something went wrong with your upload!"}
end

这行得通,而且它完全按照它应该做的那样做。但是,当我添加 respond_to 来捕获 HTML 请求时,它完全失败了(尽管 HTML 部分有效。)

respond_to do |format|
    if @image.save
        format.html {redirect_to(edit_product_path(@image.product), :notice => "Your image was added successfully.")}
        format.json {render :status => "Successfully uploaded image!"}
    else
        format.html {redirect_to(edit_product_path(@image.product), :alert => "An error occurred while attempting to upload your image. Please try again.")}
        format.json {render :status => "Something went wrong with your upload!"}
    end 
end

有什么想法可能是错的吗?我觉得我忽略了一些简单的事情。谢谢。

编辑 - 问题已解决

我认为这是我一直忽略的一件愚蠢的事情。原来请求是 HTML,而不是 JSON,这是因为上传需要内容类型为 multipart/form-data,respond_to 触发了 HTML。

【问题讨论】:

  • Firebug 简单显示:JSON.parse: unexpected character return window.JSON.parse(data);

标签: ruby-on-rails ruby-on-rails-3 json


【解决方案1】:

渲染需要一个状态码,所以下面的代码不起作用

format.json {render :status => "Something went wrong with your upload!"}

你可以写成

format.json {render :error => "Something went wrong with your upload!", :status => :bad_request }

【讨论】:

    【解决方案2】:

    你需要将响应渲染成 json

    # old
    format.json {render :status => "Successfully uploaded image!"}
    
    # new
    format.json { render(:json => { :status => "Successfully uploaded image!" }) }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      • 2015-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多