我在關聯陣列中回圈并將每個子陣列添加為表中的一行。
該表中的最后一列是一個按鈕,我想用它來從資料庫中的父陣列中洗掉該陣列。
這是我的標記:
<?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' );
我目前在控制臺中收到 admin-ajax.php 的 404 錯誤。
uj5u.com熱心網友回復:
你寫的檔案名不正確。
代替
admin_url( 'admin_ajax.php' )
有了這個
admin_url( 'admin-ajax.php' )
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338078.html
標籤:阿贾克斯 WordPress的 关联数组 后元 wp-enqueue-scripts
