REST API学习曲线


REST API learning curve

我是后端的新手,试图构建一个REST API。我在从ajax调用中检索请求数据时遇到问题。

<?php
$logfile = fopen("log.txt", "w");
fwrite($logfile, "testing'n");
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
$req_dump = print_r( $input, true );
fwrite($logfile, $req_dump . "'n");
fclose($logfile);
?>

我的电话是这样的:

$.ajax({
  dataType: "json",
  type: "GET",
  url: "http://example.com/api.php",
  data: {data:"data"},
  success: function(){ console.log('success'); }
});

我的log.txt文件只得到文本"testing",但没有任何内容来指示传递的对象{data:"data"}。我在这里跳过了哪些步骤?

您正在做的ajax是一个get request,对象数据作为查询字符串在url中发送:/api.php?data=data,在php中作为查询字符串发送的数据存储在$_GET

试试这个:

<?php
$logfile = fopen("log.txt", "w");
fwrite($logfile, "testing'n");
$method = $_SERVER['REQUEST_METHOD'];
//$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_encode($_GET,true);
$req_dump = print_r( $input, true );
fwrite($logfile, $req_dump . "'n");
fclose($logfile);