在这种情况下,不必使用wp\\u localize\\u脚本,您可以将js变量挂接到wp\\u头,这样所有js文件都可以使用它,如:
function my_js_variables(){ ?>
<script type="text/javascript">
var ajaxurl = \'<?php echo admin_url( "admin-ajax.php" ); ?>\';
var ajaxnonce = \'<?php echo wp_create_nonce( "itr_ajax_nonce" ); ?>\';
</script><?php
}
add_action ( \'wp_head\', \'my_js_variables\' )
正如@Weston Ruter所建议的,您应该对变量进行json编码:
add_action ( \'wp_head\', \'my_js_variables\' );
function my_js_variables(){ ?>
<script type="text/javascript">
var ajaxurl = <?php echo json_encode( admin_url( "admin-ajax.php" ) ); ?>;
var ajaxnonce = <?php echo json_encode( wp_create_nonce( "itr_ajax_nonce" ) ); ?>;
var myarray = <?php echo json_encode( array(
\'foo\' => \'bar\',
\'available\' => TRUE,
\'ship\' => array( 1, 2, 3, ),
) ); ?>
</script><?php
}