首页 > 解决方案 > 如何将 JSON 数据从 CodeIgniter 返回到 Google Apps 脚本?

问题描述

所以我们一直在用 Google Apps Script 制作一个聊天机器人,它的功能之一是显示来自数据库(在线托管)的信息。该脚本向我们的 CodeIgniter 程序中的控制器函数发送 POST 请求:

function do_post(name, status, duration) {
// Make a POST request with a JSON payload.
var data = {
    'name': name,
    'status': status,
    'key' : api_key,
    'duration' : duration
};
var options = {
    'method' : 'post',
    'contentType': 'application/json',
    'muteHttpExceptions' : true,
    // Convert the JavaScript object to a JSON string.
    'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch('https://www.domainname.com/bot/index.php/bot/process/', options);
Logger.log(response);
return response;
}

上面的函数使用 CI 中的 process() 控制器成功地将记录插入到数据库中,但问题出在我们的响应变量中。它是 HttpResponse 类型的,我们不知道如何从控制器返回该类型。我们希望我们的控制器向我们的聊天机器人返回类似 {"Response": "success"} 的内容,但我们不知道如何。我们尝试返回一个 JSON 编码的数组:

public function process()
{
    $_POST = array_replace($_POST, json_decode(file_get_contents('php://input'), true) ?? []);
    $name = $_POST["name"];
    $status = $_POST["status"];
    $api = $_POST["key"];
    $duration = $_POST["duration"];
    if ($api == api_key){
        $result = $this->bot_model->add_log();
    }
    $res_array =  array("response" => $result);
    // encode array to json
    $json = json_encode($res_array);
    return ($json);
    }
}

我们尝试使用 response.getContentText() 在我们的应用程序脚本中访问 var response,但我们得到类似“string(39)”的内容,然后是我们的 api_key 的值。我们如何从响应中访问 json 数据?

标签: phpcodeignitergoogle-apps-scriptchatbot

解决方案


您需要设置页面的 mime-type,以便可以使用Output 类中的set_content_type()方法提供 JSON 数据。

检查代码

    public function process()
{
    $_POST = array_replace($_POST, json_decode(file_get_contents('php://input'), true) ?? []);
    $name = $_POST["name"];
    $status = $_POST["status"];
    $api = $_POST["key"];
    $duration = $_POST["duration"];
    if ($api == api_key){
        $result = $this->bot_model->add_log();
    }
    
    // JSON OUTPUT
    $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode( array("response" => $result)));
  
}

推荐阅读