php - AJAX 从 Wordpress 插件调用的脚本未获取 $wpdb

标签 php ajax wordpress

我正在编写一个Wordpress插件,想使用ajax提交数据。当使用ajax在管理面板中提交表单时,出现此错误:

Fatal error: Call to a member function insert() on a non-object in /home1/crave/public_html/wp-content/plugins/MiniCMS/add_contenttype.php on line 13

这是正在调用的脚本。错误行已注释。

<?php
global $wpdb;

$name = $_POST["name"];
$id = '1';
$text_inputs = $_POST["text_inputs"];
$paragraph_inputs = $_POST["paragraph_inputs"];
$map_inputs = $_POST["map_inputs"];
$file_inputs = $_POST["file_inputs"];

$contentTypeTable = $wpdb->prefix . "minicms_content_type";

//This is line 13, the problem child:
$wpdb->insert( $contentTypeTable, array(
    'name' => $name,
    'id' => $id,
    'text_inputs' => $text_inputs,
    'paragraph_inputs' => $paragraph_inputs,
    'map_inputs' => $map_inputs,
    'file_inputs' => $file_inputs
));
?>

有人知道为什么我无法让 $wpdb 工作吗?

最佳答案

您需要以 WordPress 方式使用 ajax。

来自 WordPress 文档:

首先添加一些将触发 AJAX 请求的 JavaScript:

<?php
add_action( 'admin_footer', 'my_action_javascript' );

function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {

    var data = {
        action: 'my_action',
        whatever: 1234
    };

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    $.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});
</script>
<?php
}

然后,设置一个 PHP 函数来处理该请求:

add_action('wp_ajax_my_action', 'my_action_callback');

function my_action_callback() {
    global $wpdb; // this is how you get access to the database

    $whatever = intval( $_POST['whatever'] );

    $whatever += 10;

        echo $whatever;

    die(); // this is required to return a proper result
}

引用:
1.http://codex.wordpress.org/AJAX_in_Plugins
2.http://wp.tutsplus.com/articles/getting-started-with-ajax-wordpress-pagination/

关于php - AJAX 从 Wordpress 插件调用的脚本未获取 $wpdb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19887485/

相关文章:

php - WORDPRESS:在一个主要类别中显示子类别列表及其包含的帖子

php - 从 XML php 获取值后出现奇怪的字符

javascript - 检查时间范围是否重叠,如果为真则触发错误

javascript - 仅完成多个 ajax 请求中的最后一个

php - 使用ajax和json处理多个数据库行

jquery - 更改 jQuery 函数中的语言

php - 如何按数据库中的两列分组?

php - Laravel 属于抛出 undefined 错误

javascript - 如何从服务器发送和接收数据: python/flask/ajax/json GET POST requests

wordpress - 配置新的 wordpress 安装时出现 403 错误