【问题标题】:Fetching results using AJAX with Wordpress使用 AJAX 和 Wordpress 获取结果
【发布时间】:2015-09-17 05:51:31
【问题描述】:

我正在使用 Wordpress,并且创建了一个页面 (dm_page.php),该页面使用了 Contact form 7 插件,我在其中创建了下拉列表。在下拉列表的更改事件中,我正在点击 ajax。我在header.php 中写的ajax 代码。 ajax 提供数据的文件是getdata.php,放在主题文件夹中。

getdata.php:

<?php
global $wpdb;

$ddlval = $_POST['ddlval'];
$results = $wpdb->get_row('select * from my_dynamictest where lang="'.$ddlval.'"', ARRAY_A);

$someArray = [];
array_push($someArray,[
    'id' => $results['id'],
    'name' => $results['name']
]);

echo json_encode($someArray);
?>

这是我得到的错误:

致命错误:调用成员函数 get_row() on null in...

我无法弄清楚错误的含义。请帮忙。将我视为 Wordpress 的初学者。

【问题讨论】:

  • 这是这个页面的总代码吗?

标签: php jquery ajax wordpress


【解决方案1】:

您必须在文件开头加载require(__DIR__.'/../../../wp-load.php');

所以您的 getdata.php: 如下所示:

<?php
require(__DIR__.'/../../../wp-load.php');
global $wpdb;

$ddlval = $_POST['ddlval'];
$results = $wpdb->get_row('select * from my_dynamictest where lang="'.$ddlval.'"', ARRAY_A);

$someArray = [];
array_push($someArray,[
    'id' => $results['id'],
    'name' => $results['name']
]);

echo json_encode($someArray);
?>

【讨论】:

    【解决方案2】:

    我假设您提供的是此 AJAX 页面的全部代码。如果是这样,(可能有一个 "official" 方法来进行 AJAX 调用)但我只包含 wp-config.php 文件:

    <?php
    if(empty($_POST))
        exit;
    // If file in the themes folder: /wp-content/themes/dm_page.php: /../../wp-config.php
    // If file inside a theme in the theme folder: /wp-content/themes/mytheme/dm_page.php: /../../../wp-config.php
    require(__DIR__.'/../../../wp-config.php');
    global $wpdb; 
    $ddlval  =  $_POST['ddlval'];
    $results =  $wpdb->get_row('select * from my_dynamictest where lang="'.$ddlval.'"', ARRAY_A);
    
    $someArray = [];
    array_push($someArray,[
        'id' => $results['id'],
        'name' => $results['name']
    ]);
    
    echo json_encode($someArray);
    ?>
    

    编辑

    这里有一些显然是“官方”的添加 ajax 的方法:

    http://codex.wordpress.org/AJAX_in_Plugins

    http://www.1stwebdesigner.com/implement-ajax-wordpress-themes/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-06
      • 1970-01-01
      • 2021-11-17
      • 2018-07-08
      • 1970-01-01
      • 2012-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多