繁体   English   中英

Rails和jQuery产生406错误

[英]Rails and jQuery producing 406 error

使用jQuery提交表单时,出现406不可接受错误。 我尝试了在网络上找到的常见修补程序:

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

表演动作就是所谓的表演动作。 我已验证,这是日志

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]

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM