eldarion-ajax

2018-07-12 admin

eldarion-ajax是什么

什么是eldarion-ajax,a library for adding declarative ajax functionality to your website

eldarion-ajax介绍、eldarion-ajax使用

</script>


### [](#cdn-include)CDN Include

```text-html-basic
<script src="https://cdn.jsdelivr.net/npm/eldarion-ajax@0.16.0/js/eldarion-ajax.min.js"></script>

CommonJS

You can also just include it in your own bundle.

npm install eldarion-ajax --save

require('eldarion-ajax');  // do this in your main bundle file and you'll be all set

Actions

There are three supported actions:

  1. a.click
  2. form.submit
  3. a.cancel

a.click

Binding to the a tag’s click event where the tag has the class ajax:

<a href="/tasks/12342/done/" class="btn btn-primary ajax">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

In addition to the href attribute, you can add data-method="post" to change the default action from an HTTP GET to an HTTP POST.

form.submit

Convert any form to an AJAX form submission quite easily by adding ajax to the form’s class attribute:

<form class="form ajax" action="/tasks/create/" method="post">...</form>

When submitting this form the data in the form is serialized and sent to the server at the url defined in action using the method that was declared in the form tag.

a.cancel

Any a tag that has a data-cancel-closest attribute defined will trigger the “cancel” event handler. This simply removes from the DOM any elements found using the selector defined in the data-cancel-closest attribute:

<a href="#" data-cancel-closest=".edit-form" class="btn btn-secondary">
    Cancel
</a>

Events

These custom events allow you to customize eldarion-ajax behavior.

  1. eldarion-ajax:begin
  2. eldarion-ajax:success
  3. eldarion-ajax:error
  4. eldarion-ajax:complete
  5. eldarion-ajax:modify-data

All events are triggered on the element that is declared to be ajax. For example on an anchor:

<a href="/tasks/2323/delete/" class="ajax" data-method="post">

the trigger would be fired on the <a> element. This event, of course, bubbles up, but allows you to easily listen only for events on particular tags.

Every event also sends as its first parameter, the element itself, in case you were listening at a higher level in the chain, you still would have easy access to the relevant node.

eldarion-ajax:begin

This is the first event that fires and does so before any ajax activity starts. This allows you to setup a spinner, disable form buttons, etc. before the requests starts.

A single argument is sent with this event and is the jQuery object for the node:

$(document).on(`eldarion-ajax:begin`, function(evt, $el) {
    $el.html(`Processing...`);
});

eldarion-ajax:success

This event is triggered if the request succeeds. Four arguments are passed with this event: the jQuery object; the data returned from the server; a string describing the status; and the jqXHR object:

    $(document).on('eldarion-ajax:success', '[data-prepend-inner]', function(evt, $el, data, textStatus, jqXHR) {
        var $node = $($el.data('prepend-inner'));
        $node.data(data.html + $node.html());
    });

eldarion-ajax:error

This event is triggered if the request fails. Four arguments are also passed with this event: the jQuery object, the jqXHR object; a string describing the type of error that occurred; and an optional exception object. Possible values for the third argument (besides null) are “timeout”, “error”, “abort”, and “parsererror”. When an HTTP error occurs, the fourth argument receives the textual portion of the HTTP status, such as “Not Found” or “Internal Server Error.”

eldarion-ajax:complete

This event is triggered when the request finishes (after the above success and error events are completed). This is triggered from the document rather than the element in context as the handlers processing success messages could replace the DOM element and therefore would prevent the event from reaching your listener. The element is always passed as the first argument with this event (even if it no longer exists in the DOM). In response to a successful request, the arguments passed with this event are the same as those of the success event: the element, data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of the error event: the element, the jqXHR object, textStatus, and errorThrown.

eldarion-ajax:modify-data

This is triggered with jQuery’s triggerHandler so it functions more like a callback. If you listen for it, you have to listen on the same element that you have wired up to send AJAX data on as the event doesn’t bubble up. Also, it will send the original data that it serialized as a parameter and if you want to change the data at all, you must return new data from the function handling the event. Otherwise, the original data will be used.

Responses

There are three data attributes looked for in the response JSON.

  1. location - URL used for immediate redirection
  2. html - content used when processing html Directives
  3. fragments - additional content for the DOM

data.location

If location is found in the response JSON payload, it is expected to be a URL and the browser is immediately redirected to that location. No additional HTML processing is performed.

data.html

The data.html response element is typically used for insertion or replacement of existing DOM element content. Exactly how data.html is used depends on one or more processing directives.

Processing directives are defined by attributes added to the event-handling class="ajax" element. They are linked to handlers as described in Handlers: A Batteries-Included Framework.

Each processing directive is assigned a CSS selector. Since a CSS selector can be written to address multiple different blocks on the page at the same time, large segments of the DOM can be modified with each directive.

All processing directives are executed for each event and any number of directives may be combined.

Processing Directives

data-append

Append response JSON data.html to the element(s) found in the specified CSS selector.

<a href="/tasks/12342/done/" class="btn btn-primary ajax" data-method="post"
                                                          data-append=".done-list">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

data-clear

Clear the .html attribute of each DOM element found in the specified CSS selector.

<a href="/tasks/12342/done/" class="btn btn-primary ajax" data-method="post"
                                                          data-clear=".done-status">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

data-clear-closest

Invoke data-clear functionality using jQuery’s closest method to interpret the selector.

data-prepend

Prepend response JSON data.html to the element(s) found in the specified CSS selector.

<a href="/tasks/12342/done/" class="btn btn-primary ajax" data-method="post"
                                                          data-prepend=".done-list">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

data-refresh

Define which elements get refreshed. Matching elements are refreshed with the contents of the url defined in their data-refresh-url attribute.

<div class="done-score" data-refresh-url="/users/paltman/done-score/">...</div>

<a href="/tasks/12342/done/" class="btn btn-primary ajax" data-method="post"
                                                          data-refresh=".done-score">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

In this example, .done-score will fetch (GET) JSON from the url defined by data-refresh-url, then replace itself with the contents of response JSON data.html.

data-refresh-closest

Invoke data-refresh functionality using jQuery’s closest method to interpret the selector.

data-remove

Remove DOM elements found in the specified CSS selector.

<a href="/tasks/12342/done/" class="btn btn-primary ajax" data-method="post"
                                                          data-remove=".done-status">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

data-remove-closest

Invoke data-remove functionality using jQuery’s closest method to interpret the selector.

data-replace

Replace the element(s) found in the specified CSS selector with response JSON data.html.

<a href="/tasks/12342/done/" class="btn btn-primary ajax" data-method="post"
                                                          data-replace=".done-status">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

data-replace-closest

Invoke data-replace functionality using jQuery’s closest method to interpret the selector.

data-replace-closest-inner

Invoke data-replace-inner functionality using jQuery’s closest method to interpret the selector.

data-replace-inner

Similar to data-replace functionality, but replaces the element(s) .html attribute.

A Complex data.html Processing Directive Example

This example shows combined use of data-append, data-refresh, and data-remove attributes as data.html processing directives.

<div class="done-score" data-refresh-url="/users/paltman/done-score/">...</div>

<div class="done-list">...</div>

<div class="results"></div>

<a href="/tasks/12342/done/" class="btn btn-primary ajax" data-method="post"
                                                          data-append=".done-list"
                                                          data-refresh=".done-score"
                                                          data-remove=".results">
    <i class="fa fa-fw fa-check"></i>
    Done
</a>

It is rare to use many processing directives combined like this. Usually just one or two suffice.

data.fragments

Response JSON data.fragments should contain a list of key/value pairs where keys are the selectors to content that will be replaced, and values are the server-side rendered HTML content replacing elements that match the selection.

data.append-fragments

Similar to data.fragments. Each fragment value is appended to the element(s) found in the key CSS selector.

data.inner-fragments

Similar to data.fragments. Each fragment value replaces the .html attribute for the element(s) found in the key CSS selector.

data.prepend-fragments

Similar to data.fragments. Each fragment value is prepended to the element(s) found in the key CSS selector

Response Data Pro Tip

Both data.html and data.fragments are processed in a single response. This gives you the ability to replace a submitted form with data.html content while also updating multiple fragments of content on the page.

Action Attributes

The following attributes are used by eldarion-ajax when processing supported Actions.

data-cancel-closest

Used on an <a> anchor tag, triggers the cancel event handler, which removes from the DOM any elements found in the specified CSS selector.

<a href="#" data-cancel-closest=".edit-form" class="btn btn-secondary ajax">
    Cancel
</a>

data-method

Defines the request method, i.e. “POST”. If this attribute is not provided, the request method defaults to “GET”.

<a href="/tasks/2323/delete/" class="ajax" data-method="post">

data-refresh-url

Specify a URL which will return HTML content for the element.

<div class="done-score" data-refresh-url="/users/paltman/done-score/">...

本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处。

转载请注明:文章转载自 JavaScript中文网 [https://www.javascriptcn.com]

本文地址:https://www.javascriptcn.com/read-35805.html

文章标题:eldarion-ajax

回到顶部