jQuery Ajax请求不会触发来自Rails控制器的JS响应?
我有一个设置为响应HTML,JS和JSON请求的标准控制器:
I have a standard controller which is set up to respond to HTML, JS and JSON requests:
def picture
@picture = Picture.new params[:picture]
respond_to do |format|
if @picture.save
format.html do
logger.debug "In the HTML responder"
redirect_to @picture
end
format.json { render json: @picture, status: :created, location: @picture }
format.js { render :nothing => true }
else
# you get the idea
end
end
end
现在我正在尝试使用 $。ajax
函数向该控制器发送请求(我不能使用:remote => true
(在这种情况下-我正在尝试使ajax文件上传正常)。
Now I'm trying to send a request to that controller with the $.ajax
function (I can't use :remote => true
in this specific situation - I'm trying to make ajax file upload work).
$.ajax({
url: $("form#new_picture").attr("action"),
type: "POST",
data: formdata,
processData: false,
contentType: false
});
问题是由于某种原因我的请求被视为HTML请求。
The problem is that my request is being treated as a HTML request for some reason. How do I tell rails that I want a JS response?
顺便说一下,我在项目中使用的是jquery_ujs,因此我可以在需要时使用它提供的方法。我对JS的调整还不够好,无法完成我在这里所做的事情。
By the way, I'm using jquery_ujs in my project so I have access to the methods it provides if necessary. I'm not really good enough at JS to tweak that to do what I need here.
此解决方案无效对我来说(rails 3.1 + coffeescript)。经过大量搜索之后,我发现了一种很好的方法,并且想分享一下:
This solution didn't work for me (rails 3.1 + coffeescript). After searching quite a lot, I found the good way to do it and I wanted to share:
只需在网址末尾添加 .js即可。如此简单...;-)
Just add ".js" to the end of the url. So simple... ;-)