I am testing ajax in wordpress, and it basically works but I do not want the url to be hardcoded, so I tried using wp_localize_script to get an object to use, but I get an error saying: "ReferenceError: WPURLS is not defined" when alerting the siteurl in ajax_script.js.

functions.php

function my_scripts_method() {
    wp_enqueue_script(
        'ajax_script',
        get_stylesheet_directory_uri() . '/js/ajax_script.js',
        array( 'jquery' )
    );
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

wp_localize_script('ajax_script', 'WPURLS', array( 'siteurl' => get_option('siteurl') ));

ajax_script.js

$(function () {

    $('#vru-btn').click(function() {
        // alert('code');
        $.post( 'wp-content/themes/wpcleantheme/ajax/test.php', function(data) {
            $('#vru-div').html(data);    
        });
    });;

    alert(WPURLS.siteurl);
});

没有正确的解决方案

其他提示

wp_localize_script( 'ajax_script', 'WPURLS',array('siteurl' => get_option('siteurl')));

Then in script:

WPURLS.siteurl will contain the url.

When wp_localize_script is called, it takes your data and passes it through to the script in object form.

Also keep in mind, localize_script needs to be called AFTER a script is registered and enqueued.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top