Merge pull request #82 from 36864/dev

Add an extension to include the commonly-used X-Requested-With header
This commit is contained in:
chg20 2020-06-15 18:25:07 -07:00 committed by GitHub
commit 64f263f778
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 53 additions and 0 deletions

7
src/ext/ajax-header.js Normal file
View File

@ -0,0 +1,7 @@
htmx.defineExtension('ajax-header', {
onEvent: function (name, evt) {
if (name === "configRequest.htmx") {
evt.detail.headers['X-Requested-With'] = 'XMLHttpRequest';
}
}
});

21
test/ext/ajax-header.js Normal file
View File

@ -0,0 +1,21 @@
describe("ajax-header extension", function() {
beforeEach(function () {
this.server = makeServer();
clearWorkArea();
});
afterEach(function () {
this.server.restore();
clearWorkArea();
});
it('Sends the X-Requested-With header', function () {
this.server.respondWith("GET", "/test", function (xhr) {
xhr.respond(200, {}, xhr.requestHeaders['X-Requested-With'])
});
var btn = make('<button hx-get="/test" hx-ext="ajax-header">Click Me!</button>')
btn.click();
this.server.respond();
btn.innerHTML.should.equal("XMLHttpRequest");
});
});

View File

@ -121,6 +121,8 @@
<script src="../src/ext/include-vals.js"></script>
<script src="ext/include-vals.js"></script>
<script src="../src/ext/ajax-header.js"></script>
<script src="ext/ajax-header.js"></script>
<!-- events last so they don't screw up other tests -->
<script src="core/events.js"></script>

View File

@ -54,6 +54,7 @@ against `htmx` in each distribution
| [`rails-method`](/extensions/rails-method) | includes the `_method` parameter in requests for rails compatibility
| [`remove-me`](/extensions/remove-me) | allows you to remove an element after a given amount of time
| [`include-vals`](/extensions/include-vals) | allows you to include additional values in a request
| [`ajax-header`](/extensions/ajax-header) | includes the commonly-used X-Requested-With header that identifies ajax requests in many backend frameworks
</div>

View File

@ -0,0 +1,22 @@
---
layout: layout.njk
title: </> htmx - high power tools for html
---
## The `ajax-header` Extension
This extension adds the X-Requested-With header to requests with the value "XMLHttpRequest".
This header is commonly used by javascript frameworks to differentiate ajax requests from normal http requests.
### Usage
```html
<body hx-ext="ajax-header">
...
</body>
```
### Source
<https://unpkg.com/htmx.org/dist/ext/ajax-header.js>