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

时间:2019-05-29 21:48:06

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

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

我对fetch api比较陌生,这就是为什么我要学习它。我看过MDN,自定义钩子和rest api上的wordPress网站,搜索了网络并搜索了堆栈溢出。他们谈论的只是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

1 个答案:

答案 0 :(得分: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参数的形式提供给您。

application/json在某些方面有所不同,您可以在线阅读几篇文章,例如this one来了解这一点。您正在做的另一件事是传递序列化的JSON字符串,然后您告诉端点数据类型为wp-json。根据设计,$data API在默认情况下不会为您解析此数据。但是您仍然可以访问它。

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

例如,将您的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 ) ) ); } 回调更改为以下内容:

<?php
    // database connection and session init
    require 'main.php';

  //mailer init
 require 'phpmailer/PHPMailerAutoload.php';
  $mail = new PHPMailer;
  $mail->setFrom('myadd@mysite.gov.it');
//query
  $q="SELECT email FROM ".$genitori_table.",".$users_table." WHERE cf_g is not null";
  $q=$q." AND ".$users_table.".id_g1=".$genitori_table.".id AND ".$users_table.".stato=1";

  while($row = $retval->fetch_array()){
      echo $row['email'];
      $mail->AddBCC($row['email']);
      //$mail->addAddress($row['email']);
  }
  $mail->isHTML(true);

  $mail->Subject = 'my subject';
  $mail->Body    = 'my body';
  $mail->AltBody = 'my alt body.';


  $mail->AddAttachment('LetteraAiGenitori.pdf','lettera');
  $mail->AddAttachment('AutorizzazioneUscitaAutonomaAlunni.pdf');

  if(!$mail->send()) {
      echo 'Message could not be sent.';
      echo 'Mailer Error: ' . $mail->ErrorInfo;
  } else {
      echo 'Message has been sent';
  }
?>