magento2 ajax机制 (customer-data)

magento2 front-end大量运用了KnockoutJS,大量的数据能即时更新并且不需要刷新页面,数据无疑是通过AJAX方式获取,但为了效率,AJAX下载后数据会保存到Storage,只有被通知数据过期时才会再次从AJAX更新数据。因此并不能仅仅使用传统的AJAX,需要把流程封装起来。magento2的确提供了一套方法,无奈并没有文档说明,只能自己研究。

magento2把AJAX数据分类打包,分成若干个section,而每个section对应一个能获取数据的PHP类。所以第一步应该声明一个section与定义一个类。

用di.xml声明section并指定PHP类

<!-- Vendor/Samples/etc/frontend/di.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Customer\CustomerData\SectionPoolInterface">
        <arguments>
            <argument name="sectionSourceMap" xsi:type="array">
                <item name="book" xsi:type="string">Vendor\Samples\CustomerData\Book</item>
            </argument>
        </arguments>
    </type>
</config>

创建PHP类,必须定义getSectionData并返回array数据,它会以JSON格式提交到前端

// Vendor/Samples/CustomerData/Book.php
namespace Vendor\Samples\CustomerData;

use Magento\Customer\CustomerData\SectionSourceInterface;

class Book extends \Magento\Framework\DataObject implements SectionSourceInterface
{
    /**
     * {@inheritdoc}
     */
    public function getSectionData()
    {
        return [
            'message' => 'hello world'
        ];
    }
}

完成以上两步并清除缓存,就可以在前端任意UI组件中调用

require( [ 'ko', uiComponent, 'Magento_Customer/js/customer-data' ], function( ko , Component, customerData ) {
    return Component.extend({
        initialize: function () {
            // 获取数据是observable
            var book = customerData.get('book');
            // 创建名为message的observable,当customerData被更新(如ajax返回),会被同步到message
            this.message = ko.computed(function(){
                // 有data_id意味着数据已准备好
                if(book().data_id != undefined)
                    return book().message;
                else {
                    // reload即马上提取远程数据,更新本地缓存。在完成提取之前可先返回空值
                    customerData.reload(['book']);
                    return '';
                }
            }, this);
            
            // 使名叫book的section失效,在下次刷新页面时会自动reload
            // customerData.invalidate(['book']);
        }
    });
} );

常见问题

customer-data不会一直向后端提取数据,它会把数据放在Local Storage,如果Section改名,请求可能会一直出错,这是因为请求数据也放在Local Storage里,需要清空Local Storage才能得到更新,例如Local Storage的mage-cache-storage-section-invalidation。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值