代码之家  ›  专栏  ›  技术社区  ›  jlfenaux

406在Firefox中使用Jquery$.post但在Safari或Chrome中不使用时出现不可接受的错误

  •  4
  • jlfenaux  · 技术社区  · 15 年前

    我使用Jquery(1.3.2)$.post命令触发对rails服务器的ajax调用。

    这段代码在Safari和googlechrome(mac)上运行得很好,但当我在Firefox(3.5.7)上尝试时,我遇到了一个奇怪的“406不可接受”错误。

    在Chrome中,可接受的类型是“application/json,text/javascript, /

    我试图强制rails中的内容类型为“text/javascript”

    format.json do
       render :json => @races.to_json, :content_type => 'text/javascript'
    end
    

    在Chrome中,内容类型确实发生了变化,但在Firefox中,内容类型仍然是“text/html”。

    $.post(
        "/locator",
        params, 
        function(data){...},
        "json"
    );
    

    5 回复  |  直到 15 年前
        1
  •  4
  •   Paul Groves    15 年前

    在post调用中向URL添加.json扩展名

    $.post(
    "/locator.json"
    ...
    

    jQuery.ajaxSetup({ 
      'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
    })
    
        2
  •  4
  •   atmorell    15 年前

    我也有同样的问题。这似乎是firefox的问题。

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

    Credit goes to this blog.

    阿斯比恩·莫雷尔

        3
  •  0
  •   kgiannakakis    15 年前

    不同的浏览器看到不同的HTTP头是没有意义的。也许这是一个缓存问题。

        4
  •  0
  •   StefanS    15 年前

    我在$.ajaxSetup调用期间使用contentType选项来显式设置内容类型。跨浏览器工作: http://api.jquery.com/jQuery.ajax/

        5
  •  -1
  •   Community CDub    8 年前

    上面的建议(阿特莫雷尔,保罗格罗夫斯)都没有为我解决。。。然后我发现 jquery $.ajax not working in firefox against rails (406 response) (works in chrome & IE)

    我要说的是,我并不是在直接调用.ajax;相反,我使用的是JQuery.UI的自动完成程序:

    $(document).ready(function() {
        $("input#task_summary_task_wbs").autocomplete({
            source: "/tasks/summary.js"
        });
    });
    

    # GET /tasks/summary.js
    def summary
      @tasks = Task.find(:all,
                         :conditions => ['is_summary = true AND wbs like ?',
                                         "%#{params[:term]}%"],
                         :order => :wbs)
      respond_to do |format|
        format.js {
          render :text => @tasks.collect {|t| t.wbs_name}.to_json
        }
      end
    end
    

    洛杉矶火车站102号。