【问题标题】:Converting an ajax call to a fetch api call and pulling the information into a php function将 ajax 调用转换为 fetch api 调用并将信息拉入 php 函数
【发布时间】:2019-05-31 22:48:24
【问题描述】:

我正在尝试将 .ajax 调用转换为 fetch 调用。 ajax 可以工作,但是当我尝试在我的 wordPress php 文件中提取数据时,提取会出现 500 错误。

我对 fetch api 还很陌生,这就是我尝试学习它的原因。我查看了 MDN、wordPress 网站上的自定义钩子和 rest api,搜索了网络并搜索了堆栈溢出。他们谈论的只是ajax。我不知道我是否使用了错误的搜索词组,但我已经尝试了好几个小时并感到沮丧。

//working ajax in js file
createLike() {
    $.ajax({
        url: `${universityData.root_url}/wp-json/university/v1/manageLike`,
        type: 'POST',
        data: {'professorId' : 789},
        success: response => {
            console.log(response);
        },
        error: response => {
            console.log(response);
        }
    });

//my conversion to fetch
createLike() {
            const data = {
                'professorId' : 789,
            };
            fetch(`${universityData.root_url}/wp-json/university/v1/manageLike`, {
                headers: {
                    'X-WP-Nonce' : universityData.nonce,
                    'Content-Type' : 'application/json'
                },
                credentials: 'same-origin',
                method: 'POST', 
                body: JSON.stringify(data),
            }).then(function(response){
                return response.json();
            }).then(response => {
                console.log(response);
            }).catch(err => console.log(`error : ${err}`))
        },

//php file
function createLike($data) {
    $professor = sanatize_text_field($data['professorId']);
    wp_insert_post(array(
        'post_type' => 'like',
        'post_status' => 'publish',
        'post_title' => '3rd PHP Create Post Test',
        'meta_input' => array(
            'liked_professor_id' => $professor
        )
    ));
}

function universityLikeRoutes() {
register_rest_route('university/v1', 'manageLike', array(
    'methods' => 'POST',
    'callback' => 'createLike',
));

}

add_action('rest_api_init', 'universityLikeRoutes');

我的错误

{code: "internal_server_error", message: "The site is experiencing technical difficulties.", data: {…}, additional_errors: Array(0)}
additional_errors: []
code: "internal_server_error"
data: {status: 500}
message: "The site is experiencing technical difficulties."
__proto__: Object

【问题讨论】:

  • 好吧,您在 fetch 中设置了一个 X-WP-Nonce 标头,而您在 Ajax 中似乎没有这样做。也许与此有关?
  • 我这样做是因为我的其他 fetch 调用需要它,但后来将它注释掉了,它没有任何区别。

标签: php ajax fetch-api wordpress-rest-api


【解决方案1】:

关键是要了解$.ajax()fetch 的不同之处,以及如何在wordpress 中以不同方式处理数据。

$.ajax 将您传递给data 选项的任何内容默认转换为application/x-www-form-urlencoded MIME 类型。 $_POST 在 PHP automatically decodes indexed form variable names 中,WP_REST_Request 对象在您的回调中作为 $data 参数提供给您。

fetch 有几个不同的地方,你可以在网上的几篇文章中了解这一点,例如this one。您正在做的不同的一件事是传递一个序列化的 JSON 字符串,并且您告诉您的端点数据类型是 application/json。根据设计,wp-json API 默认情况下不会为您解析这些数据。但是您仍然可以访问它。

不要使用$data 作为回调参数,而是将其更改为WP_REST_Request 对象。然后你可以调用get_json_params 方法,并通过这种方式访问​​你传递给api的任何主体。

例如,将您的 PHP 回调更改为以下内容:

function createLike( WP_REST_Request $request ) {
    $data = $request->get_json_params();
    $professor = sanitize_text_field( $data['professorId'] );
    wp_insert_post( array(
        'post_type' => 'like',
        'post_status' => 'publish',
        'post_title' => '3rd PHP Create Post Test',
        'meta_input' => array(
            'liked_professor_id' => $professor
        )
    ) );
}

【讨论】:

  • 谢谢你这很好!仅供参考,我意识到我也拼错了 sanitize。
  • 我做了,但它不会显示,因为我的声誉还不够高。
猜你喜欢
  • 2022-11-27
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 2017-01-04
  • 2015-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多