Joomla core.js
提供全局 Joomla
对象以及客户端的核心功能:选项存储、翻译等。
要在页面上启用它,请使用 WebAssetManager $wa->useScript('core')
。
客户端选项
Joomla 提供了一种在服务器端和客户端之间共享脚本选项的通用方法。要从 php 共享脚本选项到 javascript,请添加它们
$doc = Joomla\CMS\Factory::getApplication()->getDocument();
$doc->addScriptOptions('my_extension_options', ['foo' => 'bar']);
在客户端读取选项
console.log(Joomla.getOptions('my_extension_options'));
客户端翻译
要向脚本添加翻译,请在布局中添加所需的字符串
Joomla\CMS\Language\Text::script('LANG_CONSTANT1');
Joomla\CMS\Language\Text::script('LANG_CONSTANT2');
Joomla\CMS\Language\Text::script('LANG_CONSTANT3');
在你的脚本中使用
console.log(Joomla.Text('LANG_CONSTANT1', 'Default string1'));
console.log(Joomla.Text('LANG_CONSTANT2', 'Default string2'));
console.log(Joomla.Text('LANG_CONSTANT3', 'Default string3'));
注意:仅当语言常量根本未添加时,才会回退到默认字符串。如果已添加但未翻译,则将返回未翻译的常量。
清理 Html 字符串
Joomla.sanitizeHtml()
方法清理不受信任的 HTML 字符串。并且应在渲染来自动态变量、翻译等的 HTML 时随时使用。
const myElement = document.createElement('div');
myElement.innerHTML = Joomla.sanitizeHtml(Joomla.Text('LANG_CONSTANT1', '<p>Default string1</p>'));
Joomla ajax 请求
对于简单的 GET
请求等基本操作,建议使用浏览器原生 fetch()
方法。但是,当需要更复杂的操作时,例如带有进度的上传或排队请求,Joomla 提供了 Joomla.request()
方法。它是 XMLHttpRequest
的包装器
Joomla.request()
选项
url: ''
请求 URLmethod: 'GET'
请求方法GET
(默认)、POST
等。data
要发送的数据,请参见 https://mdn.org.cn/docs/Web/API/XMLHttpRequest/send。promise: false
是否返回 Promise 实例。当为true
时,将忽略以下选项:perform
、onSuccess
、onError
、onComplete
。perform: true
立即执行请求或返回XMLHttpRequest
实例并稍后执行。headers: {}
自定义标头的对象,例如{'X-Foo': 'Bar', 'X-Bar': 'Foo'}
。onBefore: (xhr) => {}
请求之前的回调onSuccess: (response, xhr) => {}
请求成功时的回调onError: (xhr) => {}
请求错误时的回调onComplete: (xhr) => {}
请求完成时的回调,无论是否有错误
上传示例:
const formData = new FormData;
formData.append('file', fileBlob, filename);
Joomla.request({
url: 'index.php?option=com_example&task=upload.file',
method: 'POST',
promise: true,
data: formData,
onBefore(xhr) {
xhr.upload.addEventListener('progress', (event) => {
console.log('Progres', event.loaded, event.total);
});
},
}).then((xhr) => {
console.log('File uploaded');
}).catch((error) => {
console.log('File failed');
});
Joomla.enqueueRequest()
要按顺序执行的请求的 FIFO 队列。用于防止对服务器执行多个同时请求,这可能会触发其拒绝服务保护。接受与 Joomla.request()
相同的选项,但有一点不同,它要求 promise
设置为 true
。
队列示例:
Joomla.request(options1);
Joomla.request(options2);
Joomla.request(options3);