gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:42:47 27 4
gpt4 key购买 nike

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

这是接收请求的前端 Controller 的代码

<?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 请求。请阅读HERE 。此页面有分步指南。

由于您从 API 发送 JSON,所以在 AJAX 成功后您可能需要 JSON.parse()从 API 接收到的内容。

关于javascript - 如何让我的 PHP API 将 JSON 返回到 Javascript HTTP POST/GET 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32445698/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com