小编典典

WordPress自定义插件开发中的纯JavaScript基本AJAX调用

ajax

我正在开发一个自定义WordPress插件,在其中,我在主插件页面上有一些HTML表单,在后页上有一些PHP的函数,如从数据库中获取信息等。为详细解释,这里是代码。

主插件文件:

<?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 '
        <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", "SearchFunction"); // 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
            }
        </script>
    ';
//if you want only logged in users to access this function use this hook
add_action('wp_ajax_ACTION_NAME', 'searchData');

//if you want none logged in users to access this function use this hook
add_action('wp_ajax_nopriv_ACTION_NAME', 'searchData');

}
/*__________________________________________________________________*/


/*____________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 == "SearchFunction"){

    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 == "AnotherFunction"){
    echo "<div class='success'>SUCCESS: Another Function Is Working Perfectly.</div>";
}

?>

但是我的代码无法正常工作,甚至无法命中my_functions.php文件。这里有什么问题?仅需要基本步骤即可在此模式下工作。


阅读 267

收藏
2020-07-26

共1个答案

小编典典

最后,在获得 Thaikolja的帮助之后
,在这里,我将以简单的步骤分享问题的完整示例。此答案也被视为完整的基本Ajax插件示例。我现在个人建议将每个文件分开存放,以实现更好,干净和舒适的编码。

主插件文件:

<?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
});
});

感谢您阅读本文。如果您喜欢这个基本示例,请投票答疑解惑,以帮助他人。

2020-07-26