我编写了以下js代码
jQuery(".selectbox").change(function(){
var id = this.id;
var key_id=id;
var selectname=\'\';
jQuery.post(
// see tip #1 for how we declare global javascript variables
MyAjax.ajaxurl,
{
// here we declare the parameters to send along with the request
// this means the following action hooks will be fired:
// wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit
action : \'get-mata-value\',
// other parameters can be added along with "action"
prev_metakey : jQuery(this).val(),
metakey: key_id
},
function( result ) {
if(result[\'success\'] != false)
{
jQuery.each(result,function(index,value){
jQuery(\'#\' +id).append(\'<option value="\'+value+\'">\'+value+\'</option>\');
});
}
}
);
});
其功能是:
wp_localize_script( \'script\', \'MyAjax\',
array(
\'ajaxurl\' => admin_url( \'admin-ajax.php\' ),
)
);
wp_enqueue_script( \'script\', get_template_directory_uri() . \'/js/vehicle_parts.js\', array ( \'jquery\' ), 1.1, true);
add_action("wp_ajax_get-mata-value", "get_mata_value");
add_action("wp_ajax_nopriv_get-mata-value", "get_mata_value");
function get_mata_value()
{
global $wpdb;
$key=$_POST["metakey"];
$prev_value=$_POST["prev_metakey"];
$result=array();
$result=$wpdb->get_col("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = \'$key\'");
return($result);
}
当我更改选择框时,不会调用该函数。
最合适的回答,由SO网友:Welcher 整理而成
根据您的评论,我认为MyAjax变量没有使用wp_localize_script().
在您的情况下,您很可能需要以下内容:
wp_localize_script( \'script\', \'MyAjax\',
array(
\'ajaxurl\' => admin_url( \'admin-ajax.php\' ),
)
);
也就是说,我没有足够的信息来提供更详细的答案。
编辑:此和排队脚本调用应位于wp_enqueue_scripts
回调:
add_action(\'wp_enqueue_scripts, \'enqueue_my_scripts\' );
function enqueue_my_scripts() {
wp_enqueue_script( \'script\', get_template_directory_uri() . \'/js/vehicle_parts.js\', array ( \'jquery\' ), 1.1, true);
wp_localize_script( \'script\', \'MyAjax\',
array(
\'ajaxurl\' => admin_url( \'admin-ajax.php\' ),
)
);
}