点击PayPal支付选项时如何显示加载器?Django项目实现求助
解决方案
1. 调整HTML结构解决加载器覆盖问题
覆盖失效的核心原因是PayPal动态渲染的按钮默认z-index优先级较高,且加载器的父容器未设置相对定位,导致绝对定位的加载器位置/层级不符合预期,调整后的代码如下:
<!-- 新增外层包裹容器,设置相对定位作为加载器的定位基准 --> <div id="paypal-button-wrapper" style="position: relative;"> <div id="paypal-button-container"> <!-- PayPal Buttons load --> <a id="payBtn" href="somewhere" class="btn btn-success btn-lg">my custome button</a> </div> <!-- 新增加载器元素,默认隐藏,设置足够高的z-index保证覆盖PayPal按钮 --> <div id="paypal-loader" style="display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.8); align-items: center; justify-content: center; z-index: 9999;"> <!-- 此处替换为你自己的加载动画,比如CSS旋转动画或者加载GIF --> <div class="spinner-border text-primary" role="status"> <span class="visually-hidden">支付处理中...</span> </div> </div> </div>
2. 配置JS逻辑实现全按钮触发加载器
PayPal官方按钮为SDK动态生成,不能直接绑定原生点击事件,需要在PayPal按钮的渲染配置中添加对应回调:
// 你原有PayPal SDK渲染逻辑,仅需补充对应回调即可 paypal.Buttons({ // 保留你原有createOrder等基础配置 createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '你的支付金额' } }] }); }, // 点击PayPal官方按钮时触发,显示加载器 onClick: function(data, actions) { document.getElementById('paypal-loader').style.display = 'flex'; // 如果有支付前置校验逻辑,校验不通过可调用 actions.reject() 并隐藏加载器 }, // 支付授权成功后,调用你的Django后端处理逻辑 onApprove: function(data, actions) { return actions.order.capture().then(function(details) { fetch('/你的Django支付回调接口地址/', { method: 'POST', headers: { 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value, 'Content-Type': 'application/json' }, body: JSON.stringify({ order_id: data.orderID, pay_details: details }) }).then(res => res.json()).then(res => { // 后端逻辑处理完成后再执行跳转/隐藏加载器等操作 // window.location.href = '/支付成功页地址/'; }) }); }, // 用户取消支付时隐藏加载器 onCancel: function(data) { document.getElementById('paypal-loader').style.display = 'none'; }, // 支付报错时隐藏加载器 onError: function(err) { document.getElementById('paypal-loader').style.display = 'none'; // 可自定义添加错误提示逻辑 } }).render('#paypal-button-container'); // 绑定自定义按钮的点击事件,触发加载器 document.getElementById('payBtn').addEventListener('click', function(e) { e.preventDefault(); document.getElementById('paypal-loader').style.display = 'flex'; // 此处保留你原有自定义按钮的业务逻辑 // window.location.href = this.href; });
内容的提问来源于stack exchange,提问作者user15256253
相关产品推荐
相关产品推荐

