我正在尝试使用ajax WP方式,但我无法得到回复。如果我手动使用ajax并将url包含到php文件中,它可以正常工作。但是我想以“正确”的方式使用ajax。
这就是我所拥有的。
add_action('wp_ajax_get_data', 'get_data');
function get_data(){
$group = $_GET['option_group'];
$data_table = 'tablename';
// Array to hold data
$bigArray = array();
// Variable to determine the select clause
$query = "SELECT * FROM $data_table WHERE `group` = $group ";
$datas = $wpdb->get_results($query);
foreach($datas as $data) {
array_push($bigArray, $data);
}
echo json_encode($bigArray);
//Don't forget to always exit in the ajax function.
die();
}
然后请求
jQuery('#new_service #service_option_group').on('change', function() {
// Ajax query to fetch the results
jQuery.ajax({
type: 'GET',
url: ajaxurl,
data: {
action: 'get_data',
data: jQuery('#service_option_group').serialize()
},
success: function(result) {
jQuery('#new_service #service_option_region').empty();
// need to add the default option back in
var option = document.createElement('option');
var select = document.getElementById('service_option_region');
option.text = 'Select an Option'
option.value = -1;
select.appendChild(option);
// Append on the events
for (var i = 0; i < result.length; i++) {
// create and append each element
var option = document.createElement('option');
option.text = result[i].title;
option.value = result[i].id;
var select = document.getElementById('service_option_region');
select.appendChild(option);
}
},
error: function(request, status, error) {
alert(request.responseText);
}
})
});