donglin8467 2019-05-29 21:48 采纳率: 0%
浏览 100

将ajax调用转换为fetch api调用并将信息拉入php函数

I'm trying to convert an .ajax call to a fetch call. The ajax works but the fetch pulls a 500 error when I try to pull the data in my wordPress php file.

I'm fairly new to the fetch api and that is why I'm trying to learn it. I have looked at MDN, wordPress site on custom hooks and rest api, searched the web and searched stack overflow. All they talk about is ajax. I don't know if I'm using the wrong search phrase but I have been trying to figure this out for hours and frustrated.

//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');

my error

{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
  • 写回答

1条回答 默认 最新

  • doufangzhang4454 2019-05-30 17:31
    关注

    The key is understanding what $.ajax() does differently than fetch and thus how you have to handle the data differently in wordpress.

    $.ajax takes whatever you pass to the data option and converts into the application/x-www-form-urlencoded MIME type by default. $_POST in PHP automatically decodes indexed form variable names, which the WP_REST_Request object makes available to you within your callback as the $data argument.

    fetch is different in several ways, you can read about this in several articles online, such as this one. One thing you are doing differently is passing along a serialized JSON string and you are telling your endpoint that the data type is application/json. By design, the wp-json API doesn't by default parse this data for you. But you can access it nevertheless.

    Instead of using $data as your callback argument, change it to a WP_REST_Request object. Then you can call the get_json_params method, and access whatever body you passed to the api that way.

    For instance, change your PHP callback to the following:

    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
            )
        ) );
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀