关于不重新加载页面的表单提交,您必须使用 AJAX 提交值。 jQuery 有 $.ajax() 和 $.post() 方法,您可以使用它们来实现此目的。
示例(复制自Codex):
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': ajax_object.we_value // We pass php values differently!
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
});
数据提交后,需要使用wp_ajax_(action)来处理请求。
示例(复制自Codex):
<?php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) {
// Only applies to dashboard panel
return;
}
wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery') );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}
// Same handler function...
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die();
}
你可以从官方文档中得到详细的解释:https://codex.wordpress.org/AJAX_in_Plugins
而且,您可以使用update_status() 函数更新订单的订单状态。示例:
$order_id = ''; //-- received from AJAX request
$order = new WC_Order($order_id);
if (!empty($order)) {
$order->update_status( 'completed' );
}