从控制器返回数据 - Codeigniter

我试图将数据返回到我的变量 $item_id 但变量返回空。我没有以正确的方式返回数据吗??


item_id 应返回来自 serverMonitor.php 中的索引函数的“Alert”。


请指教。谢谢


项目.php


 function rest_state()

  {

     $id = 1;

     $item_id =  $this->pass_to_res($id);

     return $item_id //this should return "Alert"


  }




function pass_to_res($id)

   {

      $url = "https://example.com/serverMonitor?id=$id";

      $ch = curl_init();

      curl_setopt($ch, CURLOPT_URL, $url);

      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

      $result = curl_exec($ch);

      curl_close ($ch);

      return $result;

   }

serverMonitor.php


 function index() {


        $id = htmlentities($_GET['id']);

        $word = "Alert";

        return $word;

    }


开满天机
浏览 107回答 1
1回答

繁星点点滴滴

函数的返回值并不总是对访问者可见。您应该使用 echo、print 或 print_r。 function index() {        $id = htmlentities($_GET['id']);        $word = "Alert";        echo $word;        return true;    }你也可以使用 JSON with json_encode 来编码function index() {            $id = htmlentities($_GET['id']);            $word = "Alert";            echo json_encode(['word' => $word]);            return true;        }和 json_decode 解码:function pass_to_res($id)   {      $url = "https://example.com/serverMonitor?id=$id";      $ch = curl_init();      curl_setopt($ch, CURLOPT_URL, $url);      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");      $result = curl_exec($ch);      curl_close ($ch);      $result = json_decode($result);      return isset($result['word']) ? $result['word'] : false;   }
打开App,查看更多内容
随时随地看视频慕课网APP