在WordPress插件开发中通过Vanilla JavaScript调用AJAX

时间:2020-02-29 作者:Muhammad Hassan

我是WordPress插件开发的新手,我在主插件页面上有一些HTML表单,可以从登录的管理员那里获取数据,还有一个背面页面,我在PHP中有一些不同的功能,比如从数据库中获取信息等。要详细解释,这里是代码。。。

Main Plugin File:

<?php
/*
Plugin Name: WP Testing Plugin
Plugin URI: http://www.wordpress.org/WP-Testing-Plugin
Description: A Detailed Description About This Plugin.
Author: Muhammad Hassan
Version: 0.1
Author URI: http://www.wordpress.org
*/

/*____________WP Testing Plugin Admin/Script_____________*/
function wp_testingPlugin_admin() {
    echo \'
        <form id="searchForm" onsubmit="return searchData(this)">
            <input name="WhatToSearch" type="text" />
            <input type="submit" value="Search"/>
            <input type="reset" value="Reset"/>
            <div id="showReturnData"></div>
        </form>
    \';
    echo \'
        <form id="infoForm" onsubmit="return searchInfo(this)">
            <input name="WhatToKnow" type="text" />
            <input type="submit" value="Search"/>
            <input type="reset" value="Reset"/>
            <div id="showReturnInfo"></div>
        </form>
    \';

    echo \'
        <script type="text/javascript">
            function searchData(incomingForm) {
                // Confirmation To Add A Data
                var answer = confirm("Are You Sure Want To Search?");
                if (answer){
                    // If User Click Ok Then Execute The Below Code     
                    var FD = new FormData(incomingForm); // Get FORM Element Object
                    FD.append("Function", "DataFunction"); // Adding Extra Data In FORM Element Object To Hit Only This Function In Ajax Call File
                    var ajx = new XMLHttpRequest();
                    ajx.onreadystatechange = function () {
                        if (ajx.readyState == 4 && ajx.status == 200) {
                            document.getElementById("showReturnData").innerHTML = ajx.responseText;             
                        }
                    };
                    ajx.open("POST", "\'.plugin_dir_url( __FILE__ ).\'my_functions.php", true);
                    ajx.send(FD);
                    document.getElementById("showReturnData").innerHTML = "<div class="error">ERROR: AJAX Did Not Respond.</div>";
                }
                return false; // For Not To Reload Page
            }


            function searchInfo(incomingForm) {
                // Confirmation To Add A Data
                var answer = confirm("Are You Sure Want To Search?");
                if (answer){
                    // If User Click Ok Then Execute The Below Code     
                    var FD = new FormData(incomingForm); // Get FORM Element Object
                    FD.append("Function", "InfoFunction"); // Adding Extra Data In FORM Element Object To Hit Only This Function In Ajax Call File
                    var ajx = new XMLHttpRequest();
                    ajx.onreadystatechange = function () {
                        if (ajx.readyState == 4 && ajx.status == 200) {
                            document.getElementById("showReturnData").innerHTML = ajx.responseText;             
                        }
                    };
                    ajx.open("POST", "\'.plugin_dir_url( __FILE__ ).\'my_functions.php", true);
                    ajx.send(FD);
                    document.getElementById("showReturnInfo").innerHTML = "<div class="error">ERROR: AJAX Did Not Respond.</div>";
                }
                return false; // For Not To Reload Page
            }

        </script>
    \';
//if you want only logged in users to access this function use this hook
add_action(\'wp_ajax_searchData\', \'searchData\');
add_action(\'wp_ajax_searchInfo\', \'searchInfo\');
//if you want none logged in users to access this function use this hook
add_action(\'wp_ajax_nopriv_searchData\', \'searchData\');
add_action(\'wp_ajax_nopriv_searchInfo\', \'searchInfo\');


}
/*__________________________________________________________________*/


/*____________WP Testing Plugin Option_____________*/
//Adding "WP Testing Plugin" Menu To WordPress -> Tools
function wp_testingPlugin() {
    //  add_management_page( $page_title, $menu_title, $capability, $menu_slug, $function);                  Menu Under Tools
    add_management_page("WP Testing Plugin By Hassan", "WP Testing Plugin", \'activate_plugins\', "WP-Testing-Plugin", "wp_testingPlugin_admin");
}
add_action(\'admin_menu\', \'wp_testingPlugin\');
/*__________________________________________________________________*/
?>
这是my_functions.php 文件

<?php
/****************************************************************************/
//Garb The Function Parameter
/****************************************************************************/
$Function = $_POST[\'Function\'];


/****************************************************************************/
// Run Search Function
/****************************************************************************/
if ($Function == "DataFunction"){

    if(!isset($_POST[\'WhatToSearch\'])){
        $WhatToSearch = "Nothing";
    } else {
        $WhatToSearch = $_POST[\'WhatToSearch\'];
    }

    echo "<div class=\'success\'>SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToSearch.".</div>";
}

/****************************************************************************/
// Run Another Function
/****************************************************************************/
if ($Function == "InfoFunction"){

    if(!isset($_POST[\'WhatToKnow\'])){
        $WhatToKnow = "Nothing";
    } else {
        $WhatToKnow = $_POST[\'WhatToKnow\'];
    }

    echo "<div class=\'success\'>SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToKnow.".</div>";
}

?>
但我的代码不起作用my_functions.php 文件偶数。这里有什么问题?只需要基本步骤就可以在这种模式下工作。目前,我甚至不确定我是否正确实现了这一点,因为我以前从未使用过WP-AJAX。所以现在,我的目标只是让一个基本的例子起作用。我非常感谢您对如何实现这一目标的任何建议。

非常感谢。

2 个回复
最合适的回答,由SO网友:Muhammad Hassan 整理而成

最后,在尽了最大努力之后,我在这里以简单的步骤分享我的问题的完整基本示例。这个答案也被认为是一个完整的Ajax插件示例。我现在建议将每个文件分开,以便更好、干净和舒适地编码。。。

Main Plugin File:

<?php
/*
Plugin Name: WP Testing Plugin
Plugin URI: http://www.wordpress.org/WP-Testing-Plugin
Description: A Detailed Description About This Plugin.
Author: Muhammad Hassan
Version: 0.1
Author URI: http://www.wordpress.org
*/

// Calling All PHP File To Load
include(\'my_functions.php\');

/*____________WP Testing Plugin Admin/Script_____________*/
function wp_testingPlugin_admin() {
    echo \'
        <form id="searchForm">
            <input name="WhatToSearch" type="text" />
            <input type="submit" value="Search"/>
            <input type="reset" value="Reset"/>
            <div id="showReturnData"></div>
        </form>
    \';
}
/*__________________________________________________________________*/

/*____________WP Testing Plugin Option_____________*/
//Adding "WP Testing Plugin" Menu To WordPress -> Tools
function wp_testingPlugin() {
    //  add_management_page( $page_title, $menu_title, $capability, $menu_slug, $function);                  Menu Under Tools
    add_management_page("WP Testing Plugin By Hassan", "WP Testing Plugin", \'activate_plugins\', "WP-Testing-Plugin", "wp_testingPlugin_admin");
}
add_action(\'admin_menu\', \'wp_testingPlugin\');
/*__________________________________________________________________*/
?>

my_functions.php

<?php
add_action( \'admin_enqueue_scripts\', \'my_enqueue\' );
function my_enqueue() {
      wp_enqueue_script( \'ajax-script\', plugin_dir_url( __FILE__ ).\'my_javascript.js\', array(\'jquery\') );
      wp_localize_script( \'ajax-script\', \'my_ajax_object\', array( \'ajax_url\' => admin_url( \'admin-ajax.php\' ) ) );
}
/****************************************************************************/
// Run Search Function
/****************************************************************************/
/* Register This Function When This File Is Loaded To Call By WordPress AJAX */
add_action(\'wp_ajax_nopriv_SearchFunction\', \'ajaxSearchFunction\'); // For Web Visitors
add_action(\'wp_ajax_SearchFunction\', \'ajaxSearchFunction\'); // For Admin User
function ajaxSearchFunction(){
    if($_POST[\'WhatToSearch\'] == ""){
        $WhatToSearch = "Nothing";
    } else {
        $WhatToSearch = $_POST[\'WhatToSearch\'];
    }
    echo "<div class=\'success\'>SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToSearch.".</div>";
}
?>

my_javascript.js

jQuery(document).ready(function() {
jQuery(\'#searchForm\').on("submit",function(e) {
var incomingData = jQuery(\'#searchForm\').serializeArray();
incomingData.push({name: \'action\', value: \'SearchFunction\'});
alert(JSON.stringify(incomingData));
jQuery.ajax({
type: \'post\',
url: my_ajax_object.ajax_url,
data: incomingData,
success: function(response) {
jQuery(\'#showReturnData\').html(response);
},
error: function(response) {
jQuery(\'#showReturnData\').html(\'<div">Error</div>\');
},
});
return false; // For Not To Reload Page
});
});
感谢您阅读本文。

SO网友:Dennis Bowtell

感谢Muhammad,您的解决方案是一个非常棒的工作框架,可以在此基础上进行真实世界的AJAX调用。我只是将此代码添加到插件主php文件中作为一个短代码,以便在前端也可以使用它。

//For front end use in production
add_shortcode(\'wp_testingPlugin_shortcode\', \'wp_testingPlugin_shortcode\');
function wp_testingPlugin_shortcode() {
    wp_enqueue_script( \'ajax-script\', plugin_dir_url( __FILE__ ).\'my_javascript.js\',  array(\'jquery\') );
    wp_localize_script( \'ajax-script\', \'my_ajax_object\', array( \'ajax_url\' => admin_url( \'admin-ajax.php\' ) ) );
    return \'<form id="searchForm">
        <input name="WhatToSearch" type="text" />
        <input type="submit" value="Search"/>
        <input type="reset" value="Reset"/>
        <div id="showReturnData"></div>
    </form>\';
}

相关推荐

插件中的AJAX失败了--但只有一个博客--不知道为什么

这似乎很难理解。我创建了一个插件,它可以在我和其他一些博客的不同安装上正常工作。但在另一个人的博客上,它失败了。在完成调试和控制台条目之后,我相信我找到了故障的根源:在流程的某个步骤中,插件使用ajax调用函数:jQuery(document).ready(function($) { var data = { \'action\': \'mp_throwcontent_2\', \'MedioPay