在wordpress插件中使用wp_remote_get时Ajax调用失败


Ajax call fails when using wp_remote_get in wordpress plugin

我的Wordpress插件中有wp_remote_get的问题。

我想做的是用ajax调用我的主公共类中的一个方法。但问题是,当wp_remote_get函数在其中使用时,调用失败。它应该执行API调用并将数据返回给jQuery。当我注释出wp_remote_get时,调用工作正常,并给出响应。有什么好主意吗?

处理调用的方法:

    public function countryLookupApiCall() {
    if (isset($_POST['action']) && isset($_POST['country'])) {
        $country = $_POST['country'];
        $apiKey = $this->getApiKey();
        $url = $this->url . $country . '/callCharges?apiKey=' . $apiKey . '&response=JSON';
        $response = wp_remote_get($url);
        echo $response;
        die();
        }
    }
jQuery:

jQuery(document).ready(function() {
jQuery("#countryLookupForm").submit(function(e){
    var country = jQuery("#selectCountry").val();
    var action = 'countryLookupResponse';
    jQuery.ajax ({
        type: 'POST',
        url: countryLookup.ajaxurl,
        dataType: 'json',
        data: {action: action, country: country},
        success: function(data) {
            //do something with this data later on
            var result = jQuery.parseJSON(data);
            }
        });
    });
});

Wordpress动作都注册得很好,因为调用工作当我不使用wp_remote_get

编辑:解决方案并不简单,我只需要添加e.preventDefault();

您需要在代码中添加错误检查。这可以帮助你找出导致问题的原因。

    public function countryLookupApiCall() {
if (isset($_POST['action']) && isset($_POST['country'])) {
    $country = $_POST['country'];
    $apiKey = $this->getApiKey();
    $url = $this->url . $country . '/callCharges?apiKey=' . $apiKey . '&response=JSON';
    $response = wp_remote_get($url);
    if (is_wp_error($response)) {
        $error_code = $response->get_error_code();
        $error_message = $response->get_error_message();
        $error_data = $response->get_error_data($error_code);
        // Process the error here....
    }
    echo $response;
    die();
    }
}

还使用echowp_remote_get result。如文档中定义的那样,wp_remote_get返回WP_Error或数组实例。所以你应该这样写:

echo $response['body'];