使用Ajax更新post_meta关联数组



我正在循环遍历关联数组,并将每个子数组作为表中的一行添加。

表中的最后一列是一个按钮,我想用它从数据库中的父数组中删除该数组。

这是我的标记:

<?php
$response_cost = get_post_meta( 379, '_wc_booking_pricing', true );
?>
<div id="response-cost" class="hidden"><?php echo json_encode( $response_cost); ?></div>
<?php
$i = 0;
foreach ($response_cost as $response) { ?> 
<tr id="array-<?php echo $i; ?>">
<!-- table construction -->
<td><button class="remove-array" data-id="<?php echo $i; ?>"><i class="fa fa-times"></i></button></td>
</tr>
<?php
$i++; 
};
?>

这是我的jQuery,负责删除子数组:

(function($) {
$(document).ready (function () {
$(function(){
var arrString= $('#response-cost').text();
const arr = JSON.parse(arrString);
$('.remove-array').click(function(){
var val = $(this).attr("data-id");
arr.splice(val, 1);
var arr_stringify = JSON.stringify(arr);
$.ajax({
url: ajax_object.ajaxurl,
type: 'POST',
data:{
action: 'update_cost_rule_table_action',
stringified_arr: arr_stringify,
},
success: function( data ){
console.log( data );
}
});
});
});
});
}) (jQuery);
下面是function.php文件中的函数:
add_action( 'wp_ajax_update_cost_rule_table_action', 'update_cost_rule_table' );
add_action( 'wp_ajax_nopriv_update_cost_rule_table_action', 'update_cost_rule_table' );
function update_cost_rule_table(){
$response_cost = json_decode($_POST['stringified_arr']);
update_field('_wc_booking_pricing', $response_cost, 379);
wp_die();
}

我是这样给脚本排队的:

function gt21_scripts() {
wp_register_script( 'cost-rule', get_template_directory_uri() . '/js/cost-rule.js', array( 'jquery' ) );
wp_enqueue_script( 'cost-rule' );
wp_localize_script( 'cost-rule', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin_ajax.php' ) ) );
};
add_action( 'wp_enqueue_scripts', 'gt21_scripts' );

我目前得到一个404错误的admin-ajax.php在我的控制台。

文件名写错了。

代替

admin_url( 'admin_ajax.php' )

admin_url( 'admin-ajax.php' )

最新更新