如何使用 ajax 请求 WHMCS 钩子函数并获取我需要的 return 数据?

How to use ajax for request the WHMCS hooks function and get my required return data?

我阅读了用于开发配置模块的 WHMCS 演示代码:

前端代码,overview.tpl

后端代码,provisioningmodule.php

但是我的代码跟在上面我想用ajax来请求,所以整个页面不会重新渲染。


我的前端 ajax 代码:

    jQuery.ajax({
        url: url,
        type: "POST",
        data: {
            ...
            qn_action: "bmc"

        },
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data, textStatus){

            console.log('ldl:',data)  // pay attention I want to console.log the return data. I wish it be the PHP return data's `templateVariables`.
            jQuery('.powercontrol').removeClass('disabled');
            jQuery(i_id).css('display', 'none');

            jQuery('#powerstatus-spinner').css('display', 'none'); // Status loading
        },
        error: function(jqXHR, e) {
            var msg = '';
            if(jqXHR.status==0){
                msg = 'You are offline!!\n Please Check Your Network.';
            }else if(jqXHR.status==404){
                msg = 'Requested URL not found.';
            }else if(jqXHR.status==500){
                msg = 'Internal Server Error.<br/>'+jqXHR.responseText;
            }else if(e=='parsererror'){
                msg = 'Error: Parsing JSON Request failed.';
            }else if(e=='timeout'){
                msg = 'Request Time out.';
            }else {
                msg = 'Unknow Error.<br/>'+x.responseText;
            }

            console.log('error: '+jqXHR.responseText);  // I wil get the error logs
            console.log('Error msg: '+msg);
        }
    })

在我的后端 PHP 代码中:

function qidicatedserver_ClientArea(array $params)
{

    // Determine the requested action and set service call parameters based on
    // the action.

    $qn_action = isset($_REQUEST['qn_action']) ? $_REQUEST['qn_action'] : '';

    $tblclients_id = isset($_REQUEST['tblclients_id']) ? $_REQUEST['tblclients_id'] : '';  


    $bmc_action = "";
    $server_name = "";
    $templateFile = 'templates/overview.tpl';
    $bmc_result = "";


    if($qn_action == "bmc"){

        $resp = array(
            'tabOverviewReplacementTemplate' => $templateFile,
            'templateVariables' => array(
                "status"=>200,
                "data"=>"my test return data"
            )
        );



        return $resp;


    }


    try {
        // Call the service's function based on the request action, using the
        // values provided by WHMCS in `$params`.


        return array(
            'tabOverviewReplacementTemplate' => $templateFile,
            'templateVariables' => array(
                'data' => array(
                    "status"=>"200",
                    "data" => array(
                        "bmc_result" => null
                    )
                ),
            ),
        );


    } catch (Exception $e) {

        //echo $e;
        // Record the error in WHMCS's module log.
        logModuleCall(
            'qidedicatedserver',
            __FUNCTION__,
            $params,
            $e->getMessage(),
            $e->getTraceAsString()
        );
        // In an error condition, display an error page.
        return array(
            'tabOverviewReplacementTemplate' => 'templates/error.tpl',
            'templateVariables' => array(
                'usefulErrorHelper' => $e->getMessage(),
            ),
        );

    }

}

当ajax请求执行时,会报错,执行以下代码:

console.log('error: '+jqXHR.responseText);  // I wil get the console log: `error: <!DOCTYPE html> \n<html lang="en">\n<head>\n    <meta char) ....` the html is the whole page's HTML
console.log('Error msg: '+msg);  // the console log: `Error msg: Error: Parsing JSON Request failed.`

所以,那里一定有问题,我的问题是如何在 WHMCS 自定义配置模块中使用 ajax 进行 HTTP 请求,但我尝试像上层一样失败。 (我试过使用表单请求PHP,那里可以得到正确的数据,但是那里会重新刷新整个页面,这不是我想要的,我不知道要刷新什么页面)

谁能告诉我如何使用 ajax 请求 WHMCS 钩子函数和 return 正确的数据?


您可以找到更多关于 WHMCS 配置模块的介绍there


EDIT-01

我试过像这样更改 return PHP 代码:

if($qn_action == "bmc"){

    $resp = array(
        'tabOverviewReplacementTemplate' => $templateFile,
        'templateVariables' => json_encode(array(
            "status"=>200,
            "data"=>"dasdas"
        ))
    );



    return $resp;


}

但还是这个错误。

将您的 Ajax/PHP 代码放在单独的文件中,而不是 _ClientArea 方法中,假设您的模块名为 'mail_service',然后创建一个文件:

\modules\servers\mail_service\for_json.php

for_json.php

<?php
#define("ADMINAREA", true);
define("CLIENTAREA", true);
#define("SHOPPING_CART", true);
require_once(__DIR__ . '/../../../init.php');
require_once(ROOTDIR . '/includes/dbfunctions.php');
#require(ROOTDIR . "/includes/orderfunctions.php");
#require(ROOTDIR . "/includes/domainfunctions.php");
#require(ROOTDIR . "/includes/configoptionsfunctions.php");
#require(ROOTDIR . "/includes/customfieldfunctions.php");
#require(ROOTDIR . "/includes/clientfunctions.php");
#require(ROOTDIR . "/includes/invoicefunctions.php");
#require(ROOTDIR . "/includes/processinvoices.php");
#require(ROOTDIR . "/includes/gatewayfunctions.php");
#require(ROOTDIR . "/includes/modulefunctions.php");
#require(ROOTDIR . "/includes/ccfunctions.php");
#require(ROOTDIR . "/includes/cartfunctions.php");
#include_once(ROOTDIR . '/includes/clientareafunctions.php');

#use WHMCS\ClientArea;
#use WHMCS\Database\Capsule;
#use WHMCS\Smarty ;
file_put_contents("C:/xampp_my/htdocs/my/sss.txt",var_export($_POST,true));
if(isset($_POST['qn_action']) && $_POST['qn_action']=="bmc")
{
    // do your job
    //header('Content-type: application/json; charset=utf-8');
    header("Content-Type: application/json", true);

    header('HTTP/1.0 200 OK');
    echo '{"menu": {"id": "file","value": "File","popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"},{"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}}}';
}
?>

并使用以下JS代码:

jQuery.ajax({
    url: "/modules/servers/mail_service/for_json.php",
    type: 'POST',
    data: {qn_action: 'bmc'},
    cache: false,
    dataType: 'json',
    success: function (data, textStatus){console.log('ldl:',data)},
    error: function(jqXHR, e){
        var msg = '';
        if(jqXHR.status==0){
            msg = 'You are offline!!\n Please Check Your Network.';
        }else if(jqXHR.status==404){
            msg = 'Requested URL not found.';
        }else if(jqXHR.status==500){
            msg = 'Internal Server Error.<br/>'+jqXHR.responseText;
        }else if(e=='parsererror'){
            msg = 'Error: Parsing JSON Request failed.';
        }else if(e=='timeout'){
            msg = 'Request Time out.';
        }else {
            msg = 'Unknow Error.<br/>'+x.responseText;
        }
        console.log('error: '+jqXHR.responseText);  // I wil get the error logs
        console.log('Error msg: '+msg);
    }
})