ReferenceError:未定义wpApiSettings

时间:2018-07-13 09:41:28

标签: wordpress-rest-api

我有一个codeigniter网站,这是我的控制人:

public function tst()
    {
        require_once( 'c:/xampp/htdocs/2/wordpress/wp-load.php' );
        $this->load->view('tst');

    }

这是tst.php的查看内容:

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    ?><!DOCTYPE html>
    <html>

    <head>

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    </head>

    <body>
   <?php
   // Register the script
    wp_register_script( 'wp-api', 'c:/xampp/htdocs/2/wordpress/wp-includes/js/wp-api.js' );

    wp_localize_script( 'wp-api', 'wpApiSettings', array(
        'root' => esc_url_raw( rest_url() ),
        'nonce' => wp_create_nonce( 'wp_rest' )
    ) );
    // Enqueued script with localized data.
    wp_enqueue_script( 'wp-api' );

        print_r( array(
            'root' => esc_url_raw( rest_url() ),
            'nonce' => wp_create_nonce( 'wp_rest' )
        ) );


    ?>

    <button type="button" onclick="myFunction()">Retrieve</button>
    <script>

    function myFunction() {


        $.ajax( {
        url: wpApiSettings.root + 'wp/v2/posts/1',
        method: 'POST',
        beforeSend: function ( xhr ) {
            xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
        },
        data:{
            'title' : 'Hello Moon'
        }
    } ).done( function ( response ) {
       alert( response );
    } );
    }
    </script>
    </body>
    </html>

这是

的输出
print_r( array(
    'root' => esc_url_raw( rest_url() ),
    'nonce' => wp_create_nonce( 'wp_rest' )
) );

 Array ( [root] => http://localhost/2/wordpress/wp-json/ [nonce] => 04864b371a )

对于此行代码,我得到的错误是ReferenceError:wpApiSettings未定义:

 url: wpApiSettings.root + 'wp/v2/posts/1',

如果wpApiSettings在php部分的代码中获得了一个值,为什么它不在javascript部分中定义?

0 个答案:

没有答案