如何使PHP API将JSON返回到Javascript HTTP POST/GET请求?
我一直在遵循本教程创建一个“api偏心web应用程序”,但是该应用程序只包括从PHP发出请求 在教程进行到一半时,您可以通过浏览器中的url发出请求,例如 以下是接收请求的前端控制器的代码如何使PHP API将JSON返回到Javascript HTTP POST/GET请求?,javascript,php,json,rest,Javascript,Php,Json,Rest,我一直在遵循本教程创建一个“api偏心web应用程序”,但是该应用程序只包括从PHP发出请求 在教程进行到一半时,您可以通过浏览器中的url发出请求,例如 以下是接收请求的前端控制器的代码 <?php // Define path to data folder define('DATA_PATH', realpath(dirname(__FILE__).'/data')); //include our models include_once 'models/TodoItem.php';
<?php
// Define path to data folder
define('DATA_PATH', realpath(dirname(__FILE__).'/data'));
//include our models
include_once 'models/TodoItem.php';
//wrap the whole thing in a try-catch block to catch any wayward exceptions!
try {
//get all of the parameters in the POST/GET request
$params = $_REQUEST;
//get the controller and format it correctly so the first
//letter is always capitalized
$controller = ucfirst(strtolower($params['controller']));
//get the action and format it correctly so all the
//letters are not capitalized, and append 'Action'
$action = strtolower($params['action']).'Action';
//check if the controller exists. if not, throw an exception
if( file_exists("controllers/{$controller}.php") ) {
include_once "controllers/{$controller}.php";
} else {
throw new Exception('Controller is invalid.');
}
//create a new instance of the controller, and pass
//it the parameters from the request
$controller = new $controller($params);
//check if the action exists in the controller. if not, throw an exception.
if( method_exists($controller, $action) === false ) {
throw new Exception('Action is invalid.');
}
//execute the action
$result['data'] = $controller->$action();
$result['success'] = true;
} catch( Exception $e ) {
//catch any exceptions and report the problem
$result = array();
$result['success'] = false;
$result['errormsg'] = $e->getMessage();
}
//echo the result of the API call
echo json_encode($result);
exit();
要调用API,需要使用JavaScript发出AJAX请求。请阅读。本页有分步指南
当您从API发送JSON时,在AJAX成功后,您可能需要从API发送接收到的内容。下面是一个简单的示例
<?php
session_start();
if(!isset($_SESSION['user'])) {
echo -1;
die;
}
$email=$_SESSION['user'];
$arr= array();
$con=mysqli_connect("localhost","usrname","password","databasename");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="select * from user where email = '$email'";
$result = mysqli_query($con,$sql);
while ( $row = mysqli_fetch_array($result)) {
$arr[] = $row['u_id'];
$arr[] = $row['f_name'];
$arr[] = $row['l_name'];
$arr[] = $row['email'];
$arr[] = $row['telephone'];
$arr[] = $row['address'];
}
echo json_encode($arr);
mysqli_close($con);?>
这里的响应包含来自数据库的信息。URL参数是php页面的URL。
我希望这能对您有所帮助。所以我让它开始工作,我尝试的是Javascript中的常规XMLHttpRequest。进程正在工作,因为数据正在保存,但没有返回任何内容。我缺少的是index.php顶部的这一行
header('Access-Control-Allow-Origin: *');
我理解*意味着所有网站都可以访问API看看php中的json_编码。这是@georoot的链接,代码已经使用了json_编码。问题似乎是关于如何从JavaScript发出适当的请求。很抱歉之前没有提到这一点,但请求将跨域发出,我认为这种方式不起作用,对吗?
header('Access-Control-Allow-Origin: *');