Dmi*_*try 1 php wordpress checkout woocommerce woocommerce-theming
在我的在线商店中,有两种标准运输方式 - 统一费率和免费送货。我添加了一个用于远程交付的插件。
因此,当客户在下订单时填写“城市”和“地址”字段时,必须添加新的送货方式。但在我选择统一费率或免费送货之前,新的送货是不可见的。
据我了解,我没有根据字段的填写自动更新运输方式。
我找到并编辑了这段代码:
add_action('wp_footer', 'woocommerce_custom_update_checkout', 50);
function woocommerce_custom_update_checkout() {
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery( document ).ready(function( $ ) {
$('#billing_address_1').click(function(){
jQuery('body').trigger('update_checkout', { update_shipping_method: true });
});
});
</script>
<?php
}
}
Run Code Online (Sandbox Code Playgroud)
但直到我第二次单击填充字段时,交付方式才会更新。
我想用 AJAX 连接。如何编辑代码以便使用 AJAX 的结果立即可见,而无需再次单击填充的字段?
目前,您必须click在billing_address_1现场才能触发事件侦听器并更新您的字段,因为您的代码是这么说的!
有多种方法可以解决该问题。例如,click您可以添加不同的事件侦听器,而不是侦听事件。
首先,您可以监听 onchange事件。当地址字段的值已更改并且用户单击/跳出该billing_address_1字段时,就会发生这种情况:
add_action('wp_footer', 'woocommerce_custom_update_checkout', 50);
function woocommerce_custom_update_checkout()
{
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery(document).ready($ => {
$('#billing_address_1').on('change', () => {
$('body').trigger('update_checkout', {
update_shipping_method: true
});
});
});
</script>
<?php
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在此处使用的另一个事件侦听器是input事件侦听器。每次billing_address_1更改字段值时都会发生这种情况。即使按下space键、backspace键等也会触发。
add_action('wp_footer', 'woocommerce_custom_update_checkout', 50);
function woocommerce_custom_update_checkout()
{
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery(document).ready($ => {
$('#billing_address_1').on('input', () => {
$('body').trigger('update_checkout', {
update_shipping_method: true
});
});
});
</script>
<?php
}
}
Run Code Online (Sandbox Code Playgroud)
另一个可能有帮助的事件是 on blurevent。当用户单击/跳出该billing_address_1字段时,此事件将触发。这个事件和on事件的区别change在于,当你监听这个事件时,即使字段的值billing_address_1没有改变,也会发生更新。
add_action('wp_footer', 'woocommerce_custom_update_checkout', 50);
function woocommerce_custom_update_checkout()
{
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery(document).ready($ => {
$('#billing_address_1').on('blur', () => {
$('body').trigger('update_checkout', {
update_shipping_method: true
});
});
});
</script>
<?php
}
}
Run Code Online (Sandbox Code Playgroud)
现在,根据您希望如何构建代码及其背后的逻辑,您可以同时使用这些事件:
add_action('wp_footer', 'woocommerce_custom_update_checkout', 50);
function woocommerce_custom_update_checkout()
{
if (is_checkout()) {
?>
<script type="text/javascript">
jQuery(document).ready($ => {
$('#billing_address_1').on('change input blur', () => {
$('body').trigger('update_checkout', {
update_shipping_method: true
});
});
});
</script>
<?php
}
}
Run Code Online (Sandbox Code Playgroud)
如何编辑代码以便使用 AJAX 的结果立即可见,而无需再次单击填充的字段?
我认为最后一个解决方案就是您正在寻找的!一起使用所有这些事件侦听器将确保您的运输方式不断更新。