Skip to content

Instantly share code, notes, and snippets.

@pgooood

pgooood/class.php

Last active Nov 25, 2020
Embed
What would you like to do?
Примеры исходного кода к статье https://pgooood.medium.com/174ac881a93a
<?php
use Bitrix\Main\Engine\Contract\Controllerable;
class ajaxTest extends \CBitrixComponent implements Controllerable {
function executeComponent(){
$this->arResult = [
'COMPONENT_ID' => $this->componentId()
,'SCRIPT_PATH' => $_SERVER['SCRIPT_NAME']
];
$this->includeComponentTemplate();
}
function configureActions(){
return [
'exampleRequest' => [
'prefilters' => []
,'postfilters' => []
]
];
}
function exampleRequestAction($componentId, $scriptCast){
if(($scriptPath = base64_decode($scriptCast))
&& ($arComponentData = self::componentData(
$componentId,
$scriptPath
))
){
/* полученный $arParams */
var_dump($arComponentData['DATA']['PARAMS']);
}
return [
/* ответ на аякс-запрос */
];
}
protected function componentId(){
$entryId = 'sometext';
$m = null;
/* вычленим только уникальную цифровую часть идентификатора */
if(preg_match(
'/^bx_(.*)_' . $entryId . '$/',
$this->getEditAreaId($entryId),
$m
)){
return $m[1];
}
}
protected static function pageComponents($scriptPath){
if(is_file($absPath = $_SERVER['DOCUMENT_ROOT'] . $scriptPath)){
$arCounter = [];
$fileContent = file_get_contents($absPath);
$arComponents = \PHPParser::ParseScript($fileContent);
foreach ($arComponents as &$r){
$arCounter[$r['DATA']['COMPONENT_NAME']]++;
/* делаем ID как в методе getEditAreaId */
$r['ID'] = abs(crc32($r['DATA']['COMPONENT_NAME']
. '_' . $arCounter[$r['DATA']['COMPONENT_NAME']]));
}
return $arComponents;
}
throw new \Exception('File [' . $scriptPath . '] not found');
}
protected static function componentData($componentId,$scriptPath){
if($componentId
&& ($arComponents = self::pageComponents($scriptPath))
){
foreach($arComponents as $arData)
if($componentId == $arData['ID'])
return $arData;
}
}
}
<?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
CJSCore::Init(['ajax']);
<?php
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true) die;
?><script>
BX.ajax.runComponentAction(
'ajaxTest'
,'exampleRequest'
,{
mode: 'class'
,data: {
componentId: <?=$arResult['COMPONENT_ID']?>
,scriptCast: '<?=base64_encode($arResult['SCRIPT_PATH'])?>'
}
})
.then(function(response){
if(response.status === 'success'){
/* запрос выполнен успешно */
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment