我如何使我的PHP API返回JSON到Javascript HTTP POST/GET请求

How do I make my PHP API return JSON to a Javascript HTTP POST/GET request?

本文关键字:HTTP Javascript POST 请求 GET JSON 何使 我的 PHP 返回 API      更新时间:2023-09-26

我一直遵循这里的教程http://code.tutsplus.com/tutorials/creating-an-api-centric-web-application--net-23417来创建一个"api偏心web应用程序",但是该应用程序只涵盖从PHP发出请求。

在教程进行到一半的时候,你可以在浏览器中通过url发出请求,例如http://localhost/simpletodo_api/?controller=todo&action=create&title=test%20title&description=test%20description&due_date=12/08/2011&username=nikko&userpass=test1234

下面是接收请求的前端控制器的代码

<?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();

所以我的问题是,我如何使用Javascript发出请求,它将返回JSON结果?

编辑:我好像忘了说这个请求是跨域的

要调用API,您需要使用JavaScript发出AJAX请求。请在这里阅读。本页有按部就班的指导。

当您从API发送JSON时,因此,在AJAX成功后,您可能需要JSON.parse()从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);?>

上面是一个简单的PHP脚本,从简单的数据库中获取用户信息。您可以使用ajax调用从javascript调用上述php脚本,如下所示:

function Get_User_Info(URL) {
    $.ajax(
            {
                type: "GET",
                url: URL,
                dataType: "text",
                success: function (response) {
                    var JSONArray = $.parseJSON(response);
                    connsole.log(JSONArray);
            });
        }
这里的

响应包含来自数据库的信息。URL参数是php页面的URL。我希望这对你有帮助。

所以我让它工作,我所尝试的是Javascript中的常规XMLHttpRequest。该进程正在工作,因为数据正在保存,但没有返回任何内容。我缺少的是index。php

顶部的这一行
header('Access-Control-Allow-Origin: *');

我明白*表示所有网站都可以访问API