Skip to content

Commit

Permalink
Making Content-Type header more intelligent
Browse files Browse the repository at this point in the history
  • Loading branch information
alassek committed May 31, 2011
1 parent b1f2f78 commit 17db09a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
10 changes: 10 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,16 @@ jQuery.rest helpers all support the new jQuery.Deferred syntax:
$.read('/tasks/{id}.json', { id: 34 }).then(function (task) { /* do something with task */ });
```

### Setting Content-Type header ###

jQuery.rest will look for a content-type setting in three places:

1. `options.contentType` if you're using the alternate syntax
2. or else `$.restSetup.contentType`
3. or else it will look for a `json` or `xml` extension on the url resource.

If all three of those sources fail, it will use the browser's default.

### Setting csrf token & method parameter ###

There is a global object called $.restSetup that you can modify in your application's Javascript startup to match your environment.
Expand Down
24 changes: 20 additions & 4 deletions jquery.rest.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@
}

$.ajax = function (settings) {
var csrfParam = new RegExp("(" + $.restSetup.csrfParam + "=)", "i");
var csrfParam = new RegExp("(" + $.restSetup.csrfParam + "=)", "i"),
userBeforeSend = settings.beforeSend,
methodOverride;

if (typeof settings.data !== "string")
if (settings.data != null) {
Expand All @@ -116,13 +118,27 @@

if ($.restSetup.useMethodOverride)
if (!/^(get|post)$/i.test(settings.type)) {
settings.beforeSend = function (xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', settings.type);
};
methodOverride = settings.type.toUpperCase();
settings.data += (settings.data ? "&" : "") + $.restSetup.methodParam + '=' + settings.type.toLowerCase();
settings.type = "POST";
}

settings.beforeSend = function (xhr) {
var context = settings.context || settings,
contentType = settings.contentType,
resourceContentType = /.*\.(json|xml)/i.exec(settings.url);

if (!contentType) contentType = $.restSetup.contentType;
if (!contentType && resourceContentType) {
contentType = 'application/' + resourceContentType[1].toLowerCase();
}
if (settings.contentType != contentType) $.extend(settings, { contentType: contentType });

if ( methodOverride ) xhr.setRequestHeader('X-HTTP-Method-Override', methodOverride);

if ( $.isFunction(userBeforeSend) ) userBeforeSend.apply(context, xhr);
}

return _ajax.call(this, settings);
}

Expand Down

0 comments on commit 17db09a

Please sign in to comment.