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

jb4*_*b44 4 ajax mobile jquery ruby-on-rails-3

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

我正在使用jquery mobile并且一切正常,但是当我在link_to上使用remote => true开关时,它不会将请求作为JS处理(它通常在桌面版本中执行).

这是链接代码:

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

它以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
Run Code Online (Sandbox Code Playgroud)

...并抱怨没有模板:

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'
Run Code Online (Sandbox Code Playgroud)


以下是事物的编码方式:

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

谢谢

小智 10

我想这会发生在JQuery Mobile和Ruby on Rails Ajax处理混乱中.我通过明确禁用表单的JQM ajax功能修复了同样的问题:

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