jQuery ajax接受属性的要点是什么?它实际上是做什么吗?

花了一个坚实的时间试图弄清楚为什么这个(coffeescript)
$.ajax
  accepts: "application/json; charset=utf-8"

做了绝对没有什么可以改变的接受头,而这一点

$.ajax
  dataType: "json"

正确设置accept头到application / json; charset = utf-8

完全混淆,我是否缺少一些东西,还是接受全年四月愚人节的笑话?

解决方法

和往常一样 documentation是你的朋友:

accepts

Default: depends on DataType

The content type sent in the
request header that tells the server what kind of response it will
accept in return. If the accepts setting needs modification,it is
recommended to do so once in the $.ajaxSetup() method.

dataType

Default: Intelligent Guess (xml,json,script,or html)

The type of data that you’re expecting back from the server. If none
is specified,jQuery will try to infer it based on the MIME type of
the response (an XML MIME type will yield XML,in 1.4 JSON will yield
a JavaScript object,in 1.4 script will execute the script,and
anything else will be returned as a string). The available types (and
the result passed as the first argument to your success callback) are:

xml“: Returns a XML document that can be processed via jQuery.

html“: Returns HTML as plain text; included script tags are evaluated
when inserted in the DOM.

script“: Evaluates the response as
JavaScript and returns it as plain text. Disables caching by appending
a query string parameter,_=[TIMESTAMP],to the URL unless the cache
option is set to true. Note: This will turn POSTs into GETs for
remote-domain requests.

json“: Evaluates the response as JSON and
returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in
a strict manner; any malformed JSON is rejected and a parse error is
thrown. (See json.org for more information on proper JSON formatting.)

jsonp“: Loads in a JSON block using JSONP. Adds an extra
?callback=? to the end of your URL to specify the callback. Disables
caching by appending a query string parameter,
_=[TIMESTAMP],to the
URL unless the cache option is set to true.

text“: A plain text
string. multiple,space-separated values: As of jQuery 1.5,jQuery can
convert a dataType from what it received in the Content-Type header to
what you require. For example,if you want a text response to be
treated as XML,use “text xml” for the dataType. You can also make a
JSONP request,have it received as text,and interpreted by jQuery as
XML: “jsonp text xml.” Similarly,a shorthand string such as “jsonp
xml” will first attempt to convert from jsonp to xml,and,failing
that,convert from jsonp to text,and then from text to xml.

现在回到你的问题。我不熟悉cofeescript,但与dataType是一个字符串相反,accept参数是一个地图,应该像这样使用:

$.ajax({
    url: ...
    dataType: 'json',accepts: {
        xml: 'text/xml',text: 'text/plain'
    }
});

相关文章

jQuery插件的种类 1、封装对象方法 这种插件是将对象方法封装起来,用于对通过选择器获取的jQuery对象进...
扩展jQuery插件和方法的作用是非常强大的,它可以节省大量开发时间。 入门 编写一个jQuery插件开始于给...
最近项目中需要实现3D图片层叠旋转木马切换的效果,于是用到了jquery.roundabout.js。 兼容性如图: ht...
一、什么是deferred对象? 开发网站的过程中,我们经常遇到某些耗时很长的javascript操作。其中,既有异...
AMD 模块 AMD(异步模块定义,Asynchronous Module Definition)格式总体的目标是为现在的开发者提供一...