1

我正在上传一些 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。

4

2 回答 2

2

渲染需要一个状态码,因此以下内容将不起作用

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

你可以把它写成

format.json {render :error => "Something went wrong with your upload!", :status => :bad_request }
于 2012-07-12T07:00:56.940 回答
0

您需要将响应呈现为 json

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

# new
format.json { render(:json => { :status => "Successfully uploaded image!" }) }
于 2012-07-12T04:49:50.753 回答