【问题标题】:Script called by AJAX from Wordpress plugin isn't getting $wpdbAJAX 从 Wordpress 插件调用的脚本没有得到 $wpdb
【发布时间】:2013-11-22 03:23:01
【问题描述】:

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

致命错误:在非对象上调用成员函数 insert() /home1/crave/public_html/wp-content/plugins/MiniCMS/add_contenttype.php 在第 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 工作吗?

【问题讨论】:

    标签: php ajax wordpress


    【解决方案1】:

    您需要以 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/

    【讨论】:

      猜你喜欢
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      • 2015-11-13
      • 2011-04-16
      • 1970-01-01
      • 2011-09-07
      相关资源
      最近更新 更多