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 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现