jQuery Ajax请求不会触发来自Rails控制器的JS响应? [英] jQuery ajax request not triggering JS response from rails controller?

查看:101
本文介绍了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... ;-)

这篇关于jQuery Ajax请求不会触发来自Rails控制器的JS响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆