如何通过代码渲染paypal智能按钮?
How to render the paypal smart buttons through code?
这是呈现贝宝智能按钮的代码:
<script src="https://www.paypal.com/sdk/js?client-id=test"></script>
<script>paypal.Buttons().render('body');</script>
但是我想通过代码来渲染它们,所以我尝试这样做:
document.body.innerHTML='<script src="https://www.paypal.com/sdk/js?client-id=test"></script>';
paypal.Buttons().render('body');
但是没有成功,我该如何实现?
将脚本元素添加到 DOM 将导致它们异步加载,无法及时让紧随其后的代码使用它们。您需要为脚本的 onload
事件使用回调函数。这是一个这样做的示例辅助函数。
//Helper function
function loadAsync(url, callback) {
var s = document.createElement('script');
s.setAttribute('src', url); s.onload = callback;
document.head.insertBefore(s, document.head.firstElementChild);
}
// Usage -- callback is inlined here, but could be a named function
loadAsync('https://www.paypal.com/sdk/js?client-id=test¤cy=USD', function() {
paypal.Buttons({
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '0.01'
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
//...
});
}
}).render('body');
});
这是呈现贝宝智能按钮的代码:
<script src="https://www.paypal.com/sdk/js?client-id=test"></script>
<script>paypal.Buttons().render('body');</script>
但是我想通过代码来渲染它们,所以我尝试这样做:
document.body.innerHTML='<script src="https://www.paypal.com/sdk/js?client-id=test"></script>';
paypal.Buttons().render('body');
但是没有成功,我该如何实现?
将脚本元素添加到 DOM 将导致它们异步加载,无法及时让紧随其后的代码使用它们。您需要为脚本的 onload
事件使用回调函数。这是一个这样做的示例辅助函数。
//Helper function
function loadAsync(url, callback) {
var s = document.createElement('script');
s.setAttribute('src', url); s.onload = callback;
document.head.insertBefore(s, document.head.firstElementChild);
}
// Usage -- callback is inlined here, but could be a named function
loadAsync('https://www.paypal.com/sdk/js?client-id=test¤cy=USD', function() {
paypal.Buttons({
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '0.01'
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
//...
});
}
}).render('body');
});