rob*_*ped 1 php ajax wordpress jquery woocommerce
我试图在 ajax 事件之后/期间更新迷你购物车 (cart_fragments)。它的工作原理是这样的。
HTML 触发器:
<a id="woomps-button-\'.$nr.\'" class="woomps-button" '.$ajax_url.' data-button-nr="'.$nr.'">
Run Code Online (Sandbox Code Playgroud)
jQuery 请求:
jQuery( document ).on('click', '.woomps-button', function() {
var nr= jQuery(this).data('button-nr');
jQuery.ajax({
url : subpost.ajax_url,
type : 'post',
data : {
action : 'woomps_update_nr',
security : subpost.security,
nr: nr
},
success : function( response ) {
window.alert(nr);
//MAYBE_code to refresh_fragments here
}
});
return false;
});
Run Code Online (Sandbox Code Playgroud)
PHP 响应程序:
function woomps_update_choosen_person () {
$p = $_POST['nr'];
if ($p == 1) {$x= "This must show in cart";}
WC()->session->set( 'woomps_limit_by_persons' , $x );
//MAYBE code to refresh_fragments here
}
Run Code Online (Sandbox Code Playgroud)
在 mini-cart.php 模板中,我有一个基于该字段的计算。
$items_left_start = WC()->session->get( 'woomps_limit_by_persons' )?: 3 ;
//Do something something here
Run Code Online (Sandbox Code Playgroud)
所以这有效,除了我需要刷新购物车,就像将商品添加到购物车时一样。我的假设是应该是来自 jQuery 的 ajax 请求,我可以将其放入成功块中?
我(认为)我想要触发的类是 thisWC_AJAX::get_refreshed_fragments();但这是从 add_action 触发的,所以我尝试了这个add_action( 'wp_ajax_nopriv_woocommerce_get_refreshed_fragments', array( 'WC_AJAX', 'get_refreshed_fragments' ) );。但它也不起作用。
我还尝试创建一个 jQuery ajax 调用,就像在 add_to_cart 按钮中那样,但它不起作用。
//MAYBE_code to refresh_fragments here
var data = {};
jQuery.post(
wc_get_refreshed_fragments_params.wc_ajax_url.toString().
replace( '%%endpoint%%', 'get_refreshed_fragments' ), data,
function( response ){
})
}
Run Code Online (Sandbox Code Playgroud)
我不完全理解这是如何工作的,如果有人有一些指示或片段,我会非常感激它。一段时间以来一直在为此苦苦挣扎。
经过一番努力,堆栈上的这个主题帮助创建了正确的代码来更新迷你购物车片段。PHP 和 jQuery 都需要。
WC_AJAX::get_refreshed_fragments()所以基本上你可以在 PHP 代码响应程序的末尾调用; 如果它来自 AJAX 调用。它不会返回到您的 PHP 响应程序代码,因此请将其放在最后。PHP 响应将结束/发送回 ; 内的 jQuery WC_AJAX::get_refreshed_fragments()。所以你还需要创建一些对此做出响应的 jQuery。这是我从主题中得到的:
var fragments = response.fragments;
if ( fragments ) {
jQuery.each(fragments, function(key, value) {
jQuery(key).replaceWith(value);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6030 次 |
| 最近记录: |