我正在使用 Jquery (1.3.2) $.post 命令触发对 Rails 服务器的 ajax 调用。
该代码在 Safari 和 Google Chrome (mac) 上运行良好,但当我在 Firefox (3.5.7) 上尝试时,出现了奇怪的“406 Not Acceptable”错误。
当我查看标题时,Firefox 表明它只接受“text/javascript”响应。响应的 Content-Type 是 'text/html;字符集=utf-8'。
在 Chrome 中,接受的类型为“application/json、text/javascript、/、text/javascript”,响应内容类型为“application/json;”字符集=utf-8'。
我尝试将 Rails 中的内容类型强制为“text/javascript”
format.json do
render :json => @races.to_json, :content_type => 'text/javascript'
end
Chrome 中的内容类型确实发生了变化,但 Firefox 中并未发生变化,它仍然是“text/html”。
这是我用来触发 ajax 调用的代码。
$.post(
"/locator",
params,
function(data){...},
"json"
);
我可以做些什么来使其在 Firefox 中正常工作吗? 谢谢
最佳答案
在调用后的 URL 中添加 .json 扩展名
$.post(
"/locator.json"
...
或者(可能更好)将以下内容添加到您的 application.js 中,为所有 ajax 请求设置 header
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})
关于jquery - 在 Firefox 中使用 Jquery $.post 时出现 406 Not Acceptable 错误,但在 Safari 或 Chrome 中则不然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2243345/