JavaScript API 比数据属性 API 更强大。 oc.request 方法可以与表单内的任何元素一起使用,或者直接用于表单元素。 当该方法与表单内部的元素一起使用时,它会被转发到该表单。
oc.request 将目标元素和 AJAX 处理程序名称作为其第一个和第二个参数。目标元素可以是一个选择器字符串或一个 HTML 元素。例如:
<form onsubmit="oc.request(this, 'onProcess'); return false;">
...oc.request 方法的第三个参数是一个选项对象。以下选项是 October CMS 框架特有的。
| Option | Description |
|---|---|
| update | an object, specifies a list partials and page elements (as CSS selectors) to update: {'partial': '#select'}. The selector string should start with a # or . character, except you may also prepend it with @ to append contents to the element, ^ to prepend, ! to replace with and = to use any CSS selector. |
| confirm | the confirmation string. If set, a confirmation dialog is displayed before the request is sent. If the user clicks the Cancel button, the request cancels. |
| data | an optional object specifying data to be sent to the server along with the form data: {var: 'value'}. You may also include files to be uploaded in this object by using Blob objects. To specify the filename of any Blob objects, simply set the filename property on the Blob object. (Eg. var blob = new Blob(variable); blob.filename = 'test.txt'; var data = {uploaded_file: blob};) |
| query | an optional object specifying data to be added to the current URL query string. |
| headers | an optional object specifying header values to be sent to the server with the request. |
| redirect | string specifying an URL to redirect the browser to after the successful request. |
| beforeUpdate | a callback function to execute before page elements are updated. The this variable inside the function resolves to the request content - an object containing 2 properties: handler and options representing the original request() parameters. |
| afterUpdate | a callback function identical to beforeUpdate except it executes after the page elements are updated. |
| success | a callback function to execute in case of a successful request. If this option is supplied it overrides the default framework functionality: the elements are not updated, the beforeUpdate and afterUpdate callbacks are not triggered, the ajax:update and ajax:update-complete events are not triggered. To call the default framework functionality, use this.success(...) inside your function. |
| error | a callback function execute in case of an error. By default the alert message is displayed. If this option is overridden the alert message won't be displayed. |
| complete | a callback function execute in case of a success or an error. |
| cancel | a callback function execute in case the user aborts the request or cancels it via a confirmation dialog. |
| form | a form element to use for sourcing the form data sent with the request, either passed as a selector string or a form element. |
| flash | when true, instructs the server to clear and send any flash messages with the response. Default: false |
| files | when true, the request will accept file uploads using the FormData interface. Default: false |
| download | when true, file downloads are accepted with a Content-Disposition response. When a string, the downloaded filename can be specified. Default: false |
| bulk | when true, the request be sent as JSON for bulk data transactions. Default: false |
| browserValidate | when true, browser-based client side validation will be performed on the request before submitting. Only applies to requests triggered in the context of a <form> element. |
| browserRedirectBack | when true and a redirect occurs, if the previous URL from the browser is available, use that in place of the redirect URL provided. Default: false. |
| message | displays a progress message with the specified text, shown while the request is running. This option is used by the flash messages features. |
| loading | an optional string or object to be displayed when a request runs. The string should be a CSS selector for an element or the object should support the show() and hide() functions to manage the visibility. |
| progressBar | enable the progress bar when an AJAX request occurs. |
这些 beforeUpdate, afterUpdate, success, error, 和 complete 选项都接受带有三个参数的函数:从服务器接收到的数据对象, HTTP 状态码和 XHR 对象。
success: function(data, responseCode, xhr) { }您还可以通过传递新函数作为选项来覆盖部分请求逻辑。这些逻辑处理器可用。
| Handler | Description |
|---|---|
| handleConfirmMessage(message, promise) | called when requesting confirmation from the user. |
| handleErrorMessage(message) | called when an error message should be displayed. |
| handleValidationMessage(message, fields) | focuses the first invalid field when validation is used. |
| handleFlashMessage(message, type) | called when a flash message is provided using the flash option (see above). |
| handleRedirectResponse(url) | called when the browser should redirect to another location. |
在发送 onDelete 请求之前请求确认。
oc.request('#myform', 'onDelete', {
confirm: 'Are you sure?',
redirect: '/dashboard'
});运行 onCalculate 处理程序,并将渲染的 calcresult 局部注入到带有 result CSS 类的页面元素中。
oc.request('#myform', 'onCalculate', {
update: { calcresult: '.result' }
})使用一些额外数据运行 onCalculate 处理器。
oc.request('#myform', 'onCalculate', { data: { value: 55 } })运行 onCalculate 处理程序并在页面元素更新之前运行一些自定义代码。
oc.request('#myform', 'onCalculate', {
update: { calcresult: '.result' },
beforeUpdate: function() { /* do something */ }
})运行 onCalculate 处理程序,如果成功,在页面元素更新后运行一些自定义代码。
oc.request('#myform', 'onCalculate', {
afterUpdate: function() { /* do something */ }
})使用 oc.ajax 方法执行无需 FORM 元素的请求。
oc.ajax('onCalculate', {
success: function() {
console.log('Finished!');
}
})运行 onCalculate 处理程序,并且如果成功,在默认的 success 函数完成之后运行一些自定义代码.
oc.request('#myform', 'onCalculate', {
success: function(data) {
this.success(data).done(function() {
// ... do something after parent success() is finished ...
});
}
})AJAX 框架在更新的元素、触发元素、表单和窗口对象上触发事件。无论使用哪种 API - 数据属性 API 还是 JavaScript API,这些事件都会被触发。
事件处理器的 event.detail 属性中提供了额外细节。除非另有说明,处理器的细节包括 context 对象、从服务器接收到的 data 对象、responseCode 以及 xhr 对象。
| Event | Description |
|---|---|
| ajax:before-send | triggered on the window object before sending the request. The handler details provide the context object. |
| ajax:before-update | triggered on the form object directly after the request is complete, but before the page is updated. |
| ajax:update | triggered on a page element after it has been updated with the framework. |
| ajax:update-complete | triggered on the window object after all elements are updated by the framework. |
| ajax:request-success | triggered on the form object after the request is successfully completed. The handler gets 5 parameters: the event object, the context object, the data object received from the server, the status text string, and the XHR object. |
| ajax:request-error | triggered on the form object if the request encounters an error. |
| ajax:error-message | triggered on the window object if the request encounters an error. The handler has a message detail with the error message returned from the server. |
| ajax:confirm-message | triggered on the window object when confirm option is given. The handler has a message detail with a text message assigned to the handler as part of confirm option. A promise detail is also provided to defer or cancel the outcome, this is useful for implementing custom confirm logic/interface instead of native javascript confirm box. |
这些事件在触发元素上触发:
| Event | Description |
|---|---|
| ajax:setup | triggered before the request is formed. The handler details provide the context object, allowing options to be modified via the context.options property. |
| ajax:promise | triggered directly before the AJAX request is sent. The handler details provide the context object. |
| ajax:fail | triggered finally if the AJAX request fails. |
| ajax:done | triggered finally if the AJAX request was successful. |
| ajax:always | triggered regardless if the AJAX request fails or was successful. |
当 ajax:update 事件在一个元素上被触发时,执行 JavaScript 代码。
document.querySelector('#result').addEventListener('ajax:update', function() {
console.log('Updated!');
});执行一个使用逻辑处理器显示闪现消息的单个请求。
oc.ajax('onDoSomething', {
flash: true,
handleFlashMessage: function(message, type) {
oc.flashMsg({ message: message, type: type });
}
});对所有 AJAX 请求全局应用配置
addEventListener('ajax:setup', function(event) {
const { options } = event.detail.context;
// Enable AJAX handling of Flash messages on all AJAX requests
options.flash = true;
// Disable the progress bar for all AJAX requests
options.progressBar = false;
// Handle Error Messages by triggering a flashMsg of type error
options.handleErrorMessage = function(message) {
oc.flashMsg({ message: message, type: 'error' });
}
// Handle Flash Messages by triggering a flashMsg of the message type
options.handleFlashMessage = function(message, type) {
oc.flashMsg({ message: message, type: type });
}
});使用事件详情中提供的 promise。
addEventListener('ajax:confirm-message', function(event) {
const { message, promise } = event.detail;
// Prevent default behavior
event.preventDefault();
// Handle promise
if (confirm(message)) {
promise.resolve();
}
else {
promise.reject();
}
});在特定 AJAX 处理程序完成更新后,对一个元素进行动画处理。
addEventListener('ajax:update-complete', function(event) {
const { handler } = event.detail.context;
// If the handler is either of the following
if (['onRemoveFromCart', 'onAddToCart'].includes(handler)) {
// Run an animation for 2 seconds
var el = document.querySelector('#miniCart');
el.classList.add('animate-shockwave');
setTimeout(function() { el.classList.remove('animate-shockwave'); }, 2000);
}
});