我如何让我的WordPress插件接收数据,并在AJAX/php请求中将其转发到需要身份验证的远程服务器?

时间:2020-06-15 作者:AviG

我写了一个Wordpress插件,它在编辑后的页面上的元框中放置了几个按钮。我要举个例子。com/wp管理/发布。php?post=数字1和;操作=编辑。我希望我的Wordpress钩子接收AJAX调用,然后向远程服务器发出请求(该服务器需要WP用户不必输入的身份验证),然后将结果返回给Wordpress用户。

我要发送的包含数据的表单代码是两个自定义HTML元素输入的数据。它们是:

class MyFormData extends HTMLElement{
    
    constructor() {
      super();      
    }

    connectedCallback(){
      const li = document.createElement(\'li\');

      const newDat = document.createElement(\'input\');
      newDat.setAttribute(\'type\',\'text\');
      newDat.setAttribute(\'name\',`title box`);
      newDat.setAttribute(\'placeholder\',`Test Data`);

      const deleteButton = document.createElement(\'button\');
      deleteButton.setAttribute(\'type\',\'button\');
      deleteButton.innerHTML = "-";
      deleteButton.addEventListener("click",function(){
        li.parentNode.remove();
      });

      li.appendChild(newDat);
      li.appendChild(deleteButton);

      this.appendChild(li);
    }
  }
customElements.define(\'form-data\',MyFormData);
以及

class DurationMenu extends HTMLElement{
    
    constructor(){
        super();
    }

    connectedCallback(){
        const amount = document.createElement(\'input\');
        amount.setAttribute(\'id\',\'selectedTime\');
        amount.setAttribute(\'type\',\'number\');
        amount.setAttribute(\'step\',5)
        amount.setAttribute(\'name\',\'duration\');
        amount.setAttribute(\'min\',5);
        amount.setAttribute(\'max\',60);
        amount.setAttribute(\'value\',15);
        this.appendChild(amount)
    }


}
customElements.define(\'duration-choice\', DurationMenu);
这两个自定义元素都显示在元数据库中。我有一个用于提交按钮的自定义元素:

import ModelObject from \'./model/modelobject.js\'

var theJson;
var data;

import {CO} from \'./Controller/controllerobject.js\';

export var c = new ModelObject();
import {grabDataForSending} from \'./Controller/wordpressrelay.js\';

export class SubmitAndCreate extends HTMLElement{
    
    constructor(){
        super();            
    }

    connectedCallback(){
        var data;
        const submitbutton = document.createElement(\'button\');
        submitbutton.setAttribute(\'type\',\'submit\');
        submitbutton.setAttribute(\'id\',\'submitButton\');
        submitbutton.innerHTML = "Begin ";

        submitbutton.addEventListener(\'click\',this.myFunc.bind(this));

        submitbutton.addEventListener(\'click\',()=>{
            document.getElementById(\'selectedTime\').value = 15;
            var dataset = document.getElementById("dataset").children;
            for(var i = 0; i < dataset.length; i++){
                document.getElementById("dataset").children[i].children[0].childNodes[0].value = \'\';    
            }

        });
        submitbutton.addEventListener(\'click\',(event)=>{
            CO.updateModelData();
            event.preventDefault();
        })

        submitbutton.addEventListener(\'click\',(event)=>{
            grabExperimentForSending();
        })


        this.appendChild(submitbutton);
    }

    gatherData(){
        
        //var enteredURL = document.getElementsByName(\'URL box\')[0].value;
        var dataAmount = document.getElementById(\'dataset\').children.length;
        var experTime = document.getElementById(\'selectedTime\').value;

        var dataObject = {
            experimentDuration : experTime,
            myData: {}
        }

        var individualDatum = [];

        for (var i = 0; i < dataAmount; i++){
            individualDatum[i] = {
                dataset: document.getElementById("dataset").children[i].children[0].childNodes[0].value
            }
        }

        dataObject.myData = individualDatum;
        var dataObjectJSON = JSON.stringify(dataObject,null,2);
        theJson = dataObjectJSON;

        

        return theJson;
    }

}
export {theJson, CO};
customElements.define(\'submit-button\', SubmitAndCreate)
我想获取输入的数据,并将其提交到外部站点,该站点通常需要密码和用户名才能从Wordpress外部登录。我想以JSon的形式提交它。如何使用Ajax和php实现这一点?

到目前为止,我的php是:

//for admin-ajax
    add_action( \'admin_enqueue_scripts\', \'my_enqueue\' );
    function my_enqueue($hook) {
        if( \'index.php\' != $hook ) {
            return;
        }
            
        wp_enqueue_script( \'ajax-script\', plugins_url( \'/wp-content/plugins/my-plugin/js/Controller/ajaxdata.js\', __FILE__ ), array(\'jquery\') );
        wp_localize_script( \'ajax-script\', \'ajax_object\',
                array( \'ajax_url\' => admin_url( \'admin-ajax.php\' ), \'c\' => c ) ); //c has the data that I need to send to the remote site\'s server
    }


    //relevant to admin-ajax
    add_action( \'wp_ajax_CBAjax\', \'CBAjax\' ); 
    
    //relevant to admin-ajax
    function CBAjax() {

        error_log(print_r($_REQUEST));
         
         if ( isset($_REQUEST) ) {

             $exper = $_REQUEST[\'experdata\'];

             error_log(print_r($exper,true));

             
             echo "The exper is " . $exper;

         }

         
         $body = array(
             \'dur\'    => $exper[\'experimentDuration\'],
             \'buckets\'=> $experdata[\'myData\']
         );


         $response = wp_remote_post( $url = "https://subdomain.example.com:8080/api/v1/data", array(
             \'body\'    => $body,
             \'headers\' => array(
                 \'Authorization\' => \'Basic \' . base64_encode( "[email protected]" . \':\' . "password!" ),
             ),
         ) );

         if($response){
            error_log(print_r($response,true));
            error_log("PING");

         }

         $respcode = wp_remote_retrieve_response_code($response);
         error_log(print_r($respcode,true));
         $ajax[\'remote_code\'] = $response[\'response\'][\'code\'];
         echo json_encode( $ajax );
         error_log(print_r($ajax,true));

        wp_die();

        }
在创建metabox时,我有:

添加操作(“admin\\u enqueue\\u scripts”、“my\\u enqueue”);添加\\u操作(“wp\\u ajax\\u CBAjax”,“CBAjax”);

这就是我如何将数据从按钮代理到管理ajax的方法。php页面:

import {c} from \'../submitbutton.js\';


function grabExperimentForSending(){
    

    $.ajax({
           url: "admin-ajax.php",
           type: "POST",
           data: c ,
           success: function (response, statusCode) {
                console.log(c.exps[0]);
                console.log(`statusCode is ${statusCode}`);
                console.log(`data is ${data}`);
           },
           error: function(jqXHR, textStatus, errorThrown) {
              console.log(`jqXHR is ${jqXHR}, textStatus is ${textStatus}, errorThrown is ${errorThrown}`);
              console.log(c.exps[0]);
           }
       });
}
从那里,它进入ajaxdata。js公司

import {c} from \'./wordpressrelay.js\';

function my_action_javascript(){
    
    $(\'#submitButton\').click( function(){
    var data = { //model
        \'action\': \'CBAjax\',

        \'experdata\': ajax_object.c
    }



    jQuery.post(ajax_object.ajax_url, data, function(response) { 
        console.log(\'Got this from the server: \' + response);
        console.log(data.experdata);
        console.log(`data[experdata] is ${data[\'experdata\']}`);
    });
});

}

export {my_action_javascript,c};
导出{grabExperimentForSending,c};

我想将数据exp(Json)发送到远程站点。目前,我只收到“错误请求”,响应为0。我没有从与远程服务器的通信中获取javascript,也没有从php获取错误日志

1 个回复
最合适的回答,由SO网友:mozboz 整理而成

在PHP中,要调用远程服务器,您可能需要查看Wordpress中可用的http和API函数:https://developer.wordpress.org/plugins/http-api/

例如,这里有一种更容易从远程服务器获取数据的方法:

$response = wp_remote_get( \'https://api.github.com/users/blobaugh\' );
$http_code = wp_remote_retrieve_response_code( $response );
这里有一种方式可以像提交表单一样发布:

$body = array(
    \'sendThisValue\'    => \'value\',
);

$args = array(
    \'body\'        => $body,
// see docs for rest of parameters here
);

$response = wp_remote_post( \'http://your-contact-form.com\', $args );

相关推荐

是否使用插件覆盖主题中的WooCommerce loop-start.php?

“我的主题”有一个覆盖内容/主题/主题名/woocommerce/循环/loop-start.php.我想使用插件覆盖此文件。我知道可以使用子主题来完成,但我想使用插件(因为我在1个插件中捆绑了许多其他修改)。我在堆栈交换上发现了其他一些类似的问题,但无法找到有效的解决方案。以下是我的尝试:使用theme_file_path:add_filter( \'theme_file_path\', \'override_woocommerce_loop_template\', 9999); fu