繁体   English   中英

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

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

我一直在这里的教程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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM