Jquery 带POST功能的Rails ajax:为什么缺少模板?
我正在使用ajax提交完成头像上传和裁剪 我通过ajax发送base64图像,然后将图像转换为carrierwave 一切正常,除了ajax响应:模板丢失 这是我的ajax调用:Jquery 带POST功能的Rails ajax:为什么缺少模板?,jquery,ruby-on-rails,ajax,Jquery,Ruby On Rails,Ajax,我正在使用ajax提交完成头像上传和裁剪 我通过ajax发送base64图像,然后将图像转换为carrierwave 一切正常,除了ajax响应:模板丢失 这是我的ajax调用: $.ajax({ type: "post", dataType: "json", url: "/profile/update_avatar", data: { image: canvas.toDataURL() } }) .done(function(data) { // You can pull
$.ajax({
type: "post",
dataType: "json",
url: "/profile/update_avatar",
data: { image: canvas.toDataURL() }
})
.done(function(data) {
// You can pull the image URL using data.url, e.g.:
$('.user-image').html('<img src="'+data.url+'" />');
});
结束
我不需要渲染模板。。。但错误在于:
Missing template profiles/update_avatar, application/update_avatar with {:locale=>[:it], :formats=>[:js, :html], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml]}.
为什么?在控制器操作方法中,您编写了
format.js
,这就是此错误的原因
将其更改为format.json{render:json=>true}
,或者在视图中创建一个名为:profiles/update_avatar.js
的文件
因此,控制器操作应如下所示:
def update_avatar
respond_to do |format|
if current_user.update_cropped_avatar(params[:image])
format.json { render :json => true } #<-------Change here
format.html { render :nothing => true, :notice => 'Update SUCCESSFUL!' }
else
format.html { render :action => "edit" }
format.json { render :json => current_user.errors, :status => :unprocessable_entity }
end
end
def更新_化身
回应待办事项|格式|
如果当前用户更新裁剪的头像(参数[:图像])
format.json{render:json=>true}true,:notice=>'updatesuccessful!'
其他的
format.html{render:action=>“edit”}
format.json{render:json=>current_user.errors,:status=>:unprocessable_entity}
结束
结束
问题在于您使用:
respond_to do |format|
format.js
我知道您向Rails发送了JSON,但似乎只有当您的化身被正确发送时,您才在处理一个标准。使用format.js
基本上会导致rails在视图
文件夹中查找action\u name.js.erb
——因此模板错误
有多种方法可以解决此问题,包括:
respond_to do |format|
format.js { render nothing: true }
修复 在与Roberto聊天后,以下是对他有效的方法:
def update_avatar
respond_to do |format|
if current_user.update_cropped_avatar(params[:image])
format.json { render :json => current_user.profile.avatar_url, :status => 200 }
format.html { render :nothing => true, :notice => 'Update SUCCESSFUL!' }
else
format.html { render :action => "edit" }
format.json { render :json => current_user.errors, :status => :unprocessable_entity }
end
end
end
在我的js中,我还有$('.user image').html('')来更新图像。如何将其与您的代码合并?使用我的代码,您仍然可以在JS中的
数据变量中获得图像对象。您需要确定的是数据对象中的内容,然后调用url
-->如果您可以将控制台.log(data)
放入您的done
JS中,并让我知道结果,我将能够更好地帮助您我正在尝试,但在您的代码中有一些我不明白的地方,我必须在哪里放置response_to:html,:json?在我的控制器的顶部?如果嵌套有问题,我无法理解为什么有三个端点。嘿,罗伯托,很抱歉-删除了不正确的端点。respond_to位于控制器的顶部-状态中也有en error,:而不是=:)
def update_avatar
respond_to do |format|
if current_user.update_cropped_avatar(params[:image])
format.json { render :json => current_user.profile.avatar_url, :status => 200 }
format.html { render :nothing => true, :notice => 'Update SUCCESSFUL!' }
else
format.html { render :action => "edit" }
format.json { render :json => current_user.errors, :status => :unprocessable_entity }
end
end
end