如何在WordPress Admin页面上将数据传递给javascript


How to pass data to javascript on a WordPress Admin page?

我正在构建一个Wordpress插件,以从选项设置页面操作Wordpress数据库中的自定义表。到目前为止,我能够查询数据库并使用结果构建一个 HTML 表。

ob_start();
// query the database and get the records
// $games contains the records
$htm .= '<table id="pl_table">';
    // header
    $htm .= '<tr>';
        foreach ( $cols as $col ) {
            $htm .= '<th>'.$col.'</th>';
        }
    $htm .= '</tr>';
    // body
    $htm .= '<tr>';
        foreach ($games as $game){
            foreach ($game as $val) {
                $htm .= '<td>'.$val.'</td>';
            }
            $htm .= '</tr>';
        }
$htm .= '</table>';
echo $htm;
$output = ob_get_contents();
ob_end_clean();
echo $output;

目前为止,一切都好。现在我想使表中的第一列成为触发 javascript 函数的按钮。

$htm .= '<tr>';
foreach ($games as $game){
    foreach ($game as $val) {
        if ($game->ID == $val){
            $htm .= '<td><button type="button"  id="btn'.$val.'" onclick="myFunction()">'.$val.'</td>';
        }
        else {
            $htm .= '<td>'.$val.'</td>';
        }
    }
    $htm .= '</tr>';
}

这是我的管理员.js文件中的功能:

function myFunction() {
    document.getElementById("tboxOut").value = jsgame.ID;
}

在我的主插件页面中,我已经将脚本文件排队。

wp_enqueue_script('pl_script',plugins_url( 'js/admin.js', __FILE__ ));

当我在浏览器中打开页面并单击第 1 列中的按钮时,该函数将触发,我可以在浏览器中对其进行调试。

现在,我需要将$game中的数据传递给此函数并填充一堆输入框,但没有运气。这是我尝试过的:

$aryGame = (array)$game;
$htm .= wp_localize_script( 'pl_script', 'jsgame',$aryGame  );
$htm .= '<td><button type="button"  id="btn'.$val.'"onclick="myFunction()">'.$val.'</td>';

但是在浏览器调试器中,我收到一个错误:未捕获的引用错误:未定义jsgame。

显然,我缺少一些关于如何将数据从PHP传递到javascript的理解。有什么想法吗?

您需要在服务器端使用正确的钩子('admin_enqueue_scripts'),为管理页面加载 js 并为其提供句柄。然后使用正确的逻辑本地化 js。在脚本中,确保 jQuery 处于无冲突模式(通过 jQuery(document).ready)。

换句话说,服务器端发生的任何事情都保留在服务器端。js 函数 (myFunction) 没有返回任何内容,因此说 $.htm = wp_localize_script() 是没有意义的。为 js 本地化的对象是数组或 json 编码(str)/decoded(obj) 类型。如果在脚本(客户端)中对该数据类型执行某些操作后,要将修改后的数据发布回服务器,则可以通过将表单提交到选项.php来实现。提交按钮/事件将触发 php 页面刷新,因此您的服务器代码可以使用新数据。但是您需要单击提交按钮,即触发 POST 事件。

它应该如下所示:

在 PHP 中

function custom_enqueue_my_script(){
    //Retrieve any options (settings) already in database.
    $options = get_option('my_option_meta_key');
    //If you need to change the data type, e.g., (json_encode/decode), do it here.
    $data_to_pass = json_encode($options);
    //Enqueue the js file
    wp_enqueue_script('script_handle', plugins_url( 'pluginname/js/or/whatever/myadmin.js', dirname(__FILE__) ) );
    //Localize the js, referencing the handle
    wp_localize_script('script_handle', 'my_local_data', $data_to_pass );
}
add_action( 'admin_enqueue_scripts', 'custom_enqueue_my_script' );
function custom_wp_settings_callback(){ //presumably, some callback in your options.php workflow.
    //Render your section, settings and controls here
    //As well as the form.
    $htm .= '<tr>';
    foreach ($games as $game){
        foreach ($game as $val) {
            if ($game->ID == $val){
                //You don't need onclick if using jquery
                $htm .= '<td><button type="button"  id="btn'.$val.'">'.$val.'</td>';
            }
            else {
                $htm .= '<td>'.$val.'</td>';
            }
        }
        $htm .= '</tr>';
    }
}

在 JS 中

function myFunction(myNewVal){
    //Do something with myNewVal, such as populating an input field within the form, which will eventually send data back to options.php (server side).
}
jQuery(document).ready(function($){
    var local_data = my_local_data;
    console.log(local_data);    //To see it working
    $('#btnMonopoly').click(function(){
        var myNewVal = $('$btnMonopoly').val();
        myFunction(myNewVal);
    });
});

该解决方案基本上基于Pippins插件的这篇博客文章。