[英]WooCommerce ajax fetch order status & redirect to url
我想使用ajax連續檢查訂單狀態,如果我得到的訂單狀態為“處理中”,那么我想將客戶重定向到特定的URL。 我嘗試了以下代碼段,但沒有用。
<script>
function fetchStatus()
{
jQuery.ajax({
url : '<?php echo site_url(); ?>/wp-admin/admin-ajax.php?action=fetch_order_status&order_id=<?php echo $order->get_order_number(); ?>',
type : 'post',
error : function(response){
console.log(response);
},
success : function( response ){
window.location.href = "url to redirect";
}
});
}
setInterval(fetchStatus, 1000);
</script>
在functions.php
:
<?php
function fetch_order_status(){
$order = wc_get_order( $_REQUEST['order_id'] );
$order_data = $order->get_data();
if($order->has_status == 'processing'){
echo $order_data['status'];
}
die();
}
add_action('wp_ajax_nopriv_fetch_order_status', 'fetch_order_status');
add_action('wp_ajax_fetch_order_status','fetch_order_status');
?>
has_status是一個方法,它接受一個參數。 它返回一個布爾值,而不是字符串。
也許嘗試$order->has_status( 'processing' );
。
另外-更新success
邏輯:
success : function( response ){
if (response === 'DESIRED_STATUS') {
window.location.href = "url to redirect";
}
}
其中, DESIRED_STATUS
是您正在等待進行重定向的狀態。
由於您正在發出HTTP請求,因此可能發生競爭情況。
<script>
function fetchStatus()
{
jQuery.ajax({
url : '<?php echo admin_url( 'admin-ajax.php' ); ?>?action=fetch_order_status&order_id=<?php echo $order->get_order_number(); ?>'
type : 'post',
error : function(response){
console.log(response);
},
success : function( response ){
if (response === 'DESIRED_STATUS') {
window.location.href = "url to redirect";
} else {
fetchStatus();
}
}
});
}
fetchStatus();
</script>
這是我所做的:
function fetchStatus()
{
jQuery.ajax({
url : '<?php echo admin_url( 'admin-ajax.php' ); ?>?action=fetch_order_status&order_id=<?php echo $order_id; ?>',
type : 'post',
dataType:"json",
error : function(response){
console.log(response);
},
success : function( response ){
console.log(response);
if (response.status == "processing") {
window.location.href = "URL to redirect";
} else {
fetchStatus();
}
}
});
}
fetchStatus();
</script>
並在function.php中:
function fetch_order_status(){
$order = wc_get_order( $_REQUEST['order_id'] );
$order_data = $order->get_data();
echo json_encode(array("status"=>$order_data['status']));
die();
}
add_action('wp_ajax_nopriv_fetch_order_status', 'fetch_order_status');
add_action('wp_ajax_fetch_order_status','fetch_order_status');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.