rails3,jquery mobile和remote => true ajax将处理称为HTML

时间:2012-02-08 22:04:52

标签: jquery ajax ruby-on-rails-3 mobile

我在这里的几篇帖子中来回走动,并检查了Railscast的移动侦测(#199)。我有一个使用jquery和ajax和format.js的rails3应用程序,并且工作正常。现在我正在尝试将应用程序扩展到移动设备。

我正在使用jquery mobile,一切都很好,但当我使用遥控器=>在link_to上切换true,它不会将请求作为JS处理(它通常在桌面版本中处理)。

以下是链接代码:

<%= link_to 'Up', '/posts/' + String(rbpost.id) + '/upvote', :remote => true, :class => 'upvote', "data-role" => "button", "data-icon" => "arrow-u", "data-iconpos" => "notext" %>

它正在以HTML格式处理

Started GET "/posts/3/upvote" for 127.0.0.1 at 2012-02-08 11:37:59 -0500

  Processing by PostsController#upvote as HTML

。 。 。并抱怨没有模板:

ActionView::MissingTemplate (Missing template posts/upvote, application/
upvote with {:handlers=>[:erb, :builder, :coffee], :formats=>[:mobile], :locale=
[:en, :en]}. Searched in:
  * "C:/rubydemo/testapp/app/views"
):
  app/controllers/posts_controller.rb:74:in `upvote'


以下是事物的编码方式:

application_controller.rb:

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :adjust_format_for_mobile

private
  # Set iPhone format if request 
  def adjust_format_for_mobile
    if mobile_request?
        if request.format == :js
            request.format = :mobilejs
        else
            request.format = :mobile
        end
    end
  end

# Return true for mobile requests 
  def mobile_request?
    return request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/(Mobile\/.+Safari)/]
    #return true
    #I set this to return true always when I'm debugging on the desktop
  end  
end

mime_types.rb:

# Be sure to restart your server when you modify this file.

# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
 Mime::Type.register_alias "text/html", :mobile
 Mime::Type.register_alias "text/javascript", :mobilejs

posts_controller.rb:

  def upvote
    @post = Post.find(params[:id])
    @post.upvote
    @post.save

    respond_to do |format|
      format.js 
      format.mobilejs
      format.html { redirect_to @post }
      format.json { render json: @post }
    end
  end

我的views / posts目录中有upvote.js.erb和upvote.mobilejs.erb。它正在注册:移动类型,但出于某种原因,在需要时不执行javascript操作。有什么想法吗?

由于

1 个答案:

答案 0 :(得分:10)

我想这是因为JQuery Mobile和Ruby on Rails Ajax处理混乱。我通过明确禁用表单的JQM ajax功能修复了同样的问题:

<%= form_for(AgendaItem.new, :remote => true, :html =>{ "data-ajax" => false}) do |f| %>