doujiao1180 2015-12-12 22:23
浏览 11
已采纳

如何使用php代码进行ajax和http请求?

I have some classes and methods which are containing some php codes. Now I want to use those PHPcodes both for ajax and http requests. How?

Should I write all my PHP codes twice? onetime for ajax requests and one time for http request?

Here is my currect structure:

/********************************************** Search.php ****/

... // some html codes

<div id="content">

<?php

if(!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && 
   strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest")
{ 
  $type = true; // true means ajax request
} else {
  $type = false; // false means http request
}

  $obj = new classname;
  $results = obj->func($type);
  echo $results;

?>

</div>

... // some html codes



/********************************************** Classname.php ****/

class classname {

  public function func($type){
    $arr = ('key1'=>'some', 'kay2'=>'data');

    if ($type){
      echo json_encode($arr);
    } else {
      return $arr;
    }

  }

}

Now I want to know, this is standard? Actually I want to use it also for a request which came from a mobile app (something like an API). I think the above code has two problem:

  1. there will be a lot of IF-statement just for detecting type of requests (in the every methods)
  2. there is just one file (class.php) for both ajax and http requests. And when I send a ajax request by for example mobile, it will process some codes which doesn't need to them at all

Well, is there any point that I need to know?

  • 写回答

3条回答 默认 最新

  • dousou3027 2015-12-12 22:56
    关注

    I would first do all the business logic, calling on your classes, without any dependency on whether you are in an ajax call or not. When all is ready for output, make the switch:

    Search.php:

    <?php
        // first do your business logic without view dependency.
        $obj = new classname;
        $results = obj->func(); // no type is passed.
    
        if(!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && 
           strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest")
        { 
            // ajax request
            echo json_encode($results);
            exit();
        } 
        // http request
    ?>
    ... // some html codes
    <div id="content">
        <?=$results?>
    </div>
    ... // some html codes
    

    Classname.php:

    <?php
    class classname {
      public function func(){
        $arr = ('key1'=>'some', 'kay2'=>'data');
        return $arr;
      }
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c