在WordPress插件中处理跨域AJAX POST请求

时间:2017-10-27 21:02:08

标签: php jquery ajax wordpress .htaccess

我有下一个情况:

  • 我有一个简单API的WP插件。
  • 此插件可以安装到具有不同文件夹结构的不同主机上的WP实例(例如WPEngine),并且无法编辑.htaccess
  • 另一个域上有一个客户端,它应该通过AJAX数据范围发送到我的插件并获取计算数据(跨域请求);

插件 - 这是我的产品。

AJAX客户端 - 另一位将使用我的“计算器”的用户。

所以问题:

  • 我应该如何在插件中捕获此请求?
  • 哪个URL应该用AJAX客户端来访问我的API?我不能使用带有处理程序的插件和文件的完整路径的URL。
  • 将会超级理解AJAX请求方法的外观。

2 个答案:

答案 0 :(得分:1)

这种方法不安全。 您应该使用WP rest API来接受跨域请求。 此外,您应该添加WP rest API附带的auth 1.0。 这是一个链接,向您展示如何将自己的端点添加到其余的api https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/

这里有链接向您展示如何使用auth 1.0进行身份验证来保护您的api。 https://wordpress.org/plugins/rest-api-oauth1/

希望这有帮助

答案 1 :(得分:0)

您需要在PHP中创建一个函数,以便对您的服务器进行API调用,并将其添加到wp_ajaxwp_ajax_nopriv挂钩。

add_action( 'wp_ajax_your_ajax_function', 'your_ajax_function' );
add_action( 'wp_ajax_nopriv_your_ajax_function', 'your_ajax_function' );
function your_ajax_function() {
    $url = 'http://www.google.com'; // url to your rest API
    if ( isset( $_POST['data'] ) ) {
        $response = wp_remote_post( $url, array( 'data' => $_POST['data'] ) );
        if ( is_wp_error( $response ) ) {
            echo $response->get_error_message();
            exit;
        }
        else {
            wp_send_json( $response );
        }
    }
}

要确保您有权访问正确的ajax路径,localize the path for ajax for use in javascript

add_action( 'wp_enqueue_scripts', 'localize_ajax' );
function localize_ajax() {
    wp_localize_script( 'jquery', 'ajaxurl', admin_url( 'admin-ajax.php' ) );
}

注意:jquery更改为您的javascript文件和/或确保在jquery加入页面后创建您的功能。

接下来,在javascript中创建你的函数,调用你的ajax函数传递data字段中的用户值并将其附加到某个事件监听器:

function yourFunction() {
  jQuery.ajax( {
    method: 'POST',
    url: ajaxurl,
    data: {
      'action' : 'your_ajax_function',
      'data' : 'test'
    },
    success: function( response ) {
      // do what you want with your response
      console.log( response );
    }
  });
}

这将返回API调用的响应,因此请使用response在DOM中填充结果。

相关问题