Wordpress admin ajax
阅读 (2101) 2015-09-29 01:44:28
Wordpress 中使用 Ajax,由于请求地址有点特殊,在Wordpress中Ajax需要自己定义一个方法,注册到admin-ajax.php中使用,方法如下
添加自定义函数到function.php,查询语句可以改成wordpres封装好的写法,以下查询只用演示用
function application_select_manufacturer() {
global $wpdb;
$id = '';
if( isset($_GET['action'])&& $_GET['action'] == 'application_select_manufacturer'){
$id = $_GET['id'] ;
$result = $wpdb->get_results("SELECT MANUFACTURER FROM _cwcustom_table WHERE DEVICE_TYPE_ID='".$id."'");
$return_code = '<option value="" selected="">Please Select One</option>';
global $previous_tableName;
$previous_tableName = '';
foreach ( $result as $table ){
foreach ($table as $tableName){
if($previous_tableName != $tableName){
$return_code .= '<option value="'.$tableName.'">'.$tableName.'</option>';
}
$previous_tableName = $tableName;
}
}
echo $return_code;
}
die();
}
将函数添加到 WordPress admin-ajax.php 接口中
//放在function.php即可
add_action( 'wp_ajax_application_select_manufacturer', 'application_select_manufacturer' );
add_action("wp_ajax_nopriv_application_select_manufacturer", "application_select_manufacturer");
AJAX查询,这里只写ajax部分,忽略获取参数及事件触发
$.ajax({
url: '<?php echo admin_url( "admin-ajax.php" )?>?action=application_select_manufacturer&id='+$(this).val(),
datatype: "json",
type: 'post',
success: function (data) {
select_device.parent().find('select.select_manufacturer').html(data);
}
})
更新于:2015-09-29 01:44:28