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

时间:2015-09-07 20:33:15

标签: javascript php json rest

我一直在关注这里的教程http://code.tutsplus.com/tutorials/creating-an-api-centric-web-application--net-23417来创建一个“api eccentric web应用程序”,但该应用程序仅涵盖从PHP发出请求。

在教程的中途,您可以在浏览器中通过网址发出请求,例如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结果?

编辑:似乎我忘记提到此请求将跨域

3 个答案:

答案 0 :(得分:1)

要调用API,您需要使用JavaScript发出AJAX请求。请阅读HERE。本页面有逐步指南。

当您从API发送JSON时,在AJAX成功之后,您可能需要JSON.parse()从API接收的内容。

答案 1 :(得分:1)

这是一个简单的例子

<?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。 我希望能帮助你。

答案 2 :(得分:0)

所以我得到了它的工作,我曾经尝试过的是Javascript中的常规XMLHttpRequest。这个过程正在运行,因为数据正在保存,但没有返回任何内容。我缺少的是来自index.php顶部的这一行

header('Access-Control-Allow-Origin: *');

我认为*表示所有网站都可以访问API