Rails和jQuery产生406错误

时间:2010-01-28 19:23:20

标签: jquery ruby-on-rails ajax

使用jQuery提交表单时出现406 Not Acceptable错误。我尝试过在网络上找到的常见修补程序:

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {
    xhr.setRequestHeader("Accept", "text/javascript");
  }
}) 

这还没有解决问题。 request.format输出text / html。我一整天都试图解决这个问题。 Rails 2.3.4,jQuery 1.3.2和jQTouch。

这是我的jquery代码:

jQuery(function () {
  $("#search").submit(function (e) {
    var $form = $(this);
    return app.search($form);
  });
});

var app = {
  search:function ($form) {
    $.ajax({

      type:$form.attr("method"), url:$form.attr("action"),
      dataType:"script", data:$form.serialize(),
      complete:function (req) {
        if (req.status === 200 || req.status === 304) {
        } else {
          alert("There was an error searching. Try again.");
          console.log(this);
        }
      }
    });    
    return false;
  }
};

表格:

  %form{:action => "/search", :method => "post", :id => "search", "accept-charset" => "utf-8"}
    %div{:style =>"margin:0;padding:0;display:inline" }
      %input{:name => "_method", :type => "hidden", :value => "put"}
      %input{:name => "authenticity_token", :type => "hidden", :value => "#{form_authenticity_token}"}
    %ul.rounded
      %li
        %input{:name => 'query', :value => '', :type => 'text', :placeholder => "Search"}

控制器代码:

  def show
    query = params[:query]
    @results = Person.search(query)
    respond_to do |wants|
      wants.html { }
      wants.js 
    end   
  end

show动作是一个叫做的动作。我已经确认,这是日志

Processing PeopleController#show (for 127.0.0.1 at 2010-01-28 14:12:19) [PUT]
  Parameters: {"authenticity_token"=>"y4kC2CZ1dnrV7LWEC2mRxv8mP499C+0HXbRVlDEuWDc=", "query"=>"purcell"}
  SQL (1.3ms)    SELECT trigger_name
 FROM all_triggers
 WHERE owner = 'PDSADMIN'
 AND trigger_name = 'PERSON_PKT'
 AND table_owner = 'PDSADMIN'
 AND table_name = 'PERSON'
 AND status = 'ENABLED'

  Person Columns (20.9ms)    select column_name as name, data_type as sql_type, data_default, nullable,
 decode(data_type, 'NUMBER', data_precision,
 'FLOAT', data_precision,
 'VARCHAR2', decode(char_used, 'C', char_length, data_length),
 'CHAR', decode(char_used, 'C', char_length, data_length),
 null) as limit,
 decode(data_type, 'NUMBER', data_scale, null) as scale
 from all_tab_columns
 where owner = 'PDSADMIN'
 and table_name = 'PERSON'
 order by column_id

  Person Load (3.7ms)   SELECT * FROM person WHERE (person.person_id IN (5554,55,5966,146)) 
Completed in 77ms (View: 20, DB: 26) | 406 Not Acceptable [http://localhost/search]

2 个答案:

答案 0 :(得分:1)

好的,我发现了我的问题。我正在使用jqtouch插件进行rails,它会自动为开发模式下的请求分配:iphone格式,这会强制我没有的format.iphone。我用这段代码来覆盖:

if request.xhr? && request.format == :iphone
  request.format = :js
end

答案 1 :(得分:0)

正确的方法是编辑(或添加)config/initializers/mime_types.rb以接受:iphone次请求。

Mime::Type.register_alias "text/javascript", :iphone