【问题标题】:AJAX request and PHP class functionsAJAX 请求和 PHP 类函数
【发布时间】:2013-07-03 13:41:04
【问题描述】:

如何从 ajax 调用中调用 PHP 类函数

animal.php文件

class animal
{     
  function getName()
  {
    return "lion";
  }
}

然后在我的ajax.php 文件中我有一个ajax 请求,需要从getName 函数中获取值

getName() 函数怎么做我可以这样做吗?

<script type=text/javascript>
  $.ajax({
    type: "POST",
    data: {
      invoiceno:jobid
    },
    url: "animal/getName",
    beforeSend: function() {
    },
    dataType: "html",
    async: false,
    success: function(data) {
      result=data;
    }
  });    
</script>

【问题讨论】:

  • 你开始的时候看起来不错,现在你只需要一个echoes getName() 的页面,当请求 URL animal/getName 时。

标签: php ajax


【解决方案1】:

我的回答和Surreal Dreams answer一样,不过是密码。

首先。类动物还可以。就这样吧:

animal.php

<?php

class animal
{     
  function getName()
  {
    return "lion";
  }
}

接下来。创建一个新的animalHandler.php 文件。

<?php
require_once 'animal.php';

if(isset( $_POST['invoiceno'] )) {
     $myAnimal = new animal();
     $result = $myAnimal->getName();
     echo $result;
}

最后。更改您的 Javascript。

<script type=text/javascript>
  $.ajax({
    type: "POST",
    data: {
      invoiceno:jobid
    },
    url: "animalHandler.php",
    dataType: "html",
    async: false,
    success: function(data) {
      result=data;
    }
  });    
</script>

原来如此。

【讨论】:

  • 谢谢大家,但我的问题是如果我必须使用 50 个 ajax 请求,我必须使用 50 个 php 文件来输出这些结果。我的疑问是我是否可以在一个名为 ajax 的类中使用所有这些函数,那么它对我来说会很棒。但我一直在codeigniter框架中使用相同的。如果我可以在普通的 php 中使用很棒的类做同样的事情。只是我想知道这是否可能在 php 中。
  • 您可以使用一个ajax.php 文件来处理所有的ajax 调用,但要注意:它会很大且无法维护。
  • 创建一个适用于多种情况的函数,并使用一些参数来访问您要检索的那个。
  • 如果在 jquery 3.4 中真是太棒了.. 它可能变成 $.post ( ajaxurl, { 'action': 'classname/foomethod', 'data': ... ))
【解决方案2】:

你需要一个额外的脚本,因为你的动物类不能自己做任何事情。

首先,在另一个脚本文件中,包含animal.php。然后创建一个动物类的对象——我们称它为 myAnimal。然后调用 myAnimal->getName() 并回显结果。这将为您的 Ajax 脚本提供响应。

使用这个新脚本作为您的 Ajax 请求的目标,而不是针对 animal.php。

【讨论】:

  • 我打算回答同样的问题,但要编写代码。也许它更有帮助。
【解决方案3】:

OOP 目前使用 php:

ajax.html 程序(客户端层)-> program.php(中间层)-> class.php(中间层)-> SQL 调用或 SP(数据库层)

OOP 目前使用 DotNet:

ajax.html 程序(客户层)-> program.aspx.vb(中间层)-> class.cls(中间层)-> SQL 调用或 SP(数据库层)

我的现实解决方案: 做OOA,不要OOP。

所以,我每个表都有一个文件 - 作为一个类 - 带有正确的 ajax 调用,并使用 POST 参数(即模式)选择相应的 ajax 调用。

/* mytable.php */

<?
session_start();
header("Content-Type: text/html; charset=iso-8859-1");
$cn=mysql_connect ($_server, $_user, $_pass) or die (mysql_error());
mysql_select_db ($_bd);   
mysql_set_charset('utf8');

//add
if($_POST["mode"]=="add")   {
    $cadena="insert into mytable values(NULL,'".$_POST['txtmytablename']."')"; 
    $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); 
};

//modify
if($_POST["mode"]=="modify")    {
    $cadena="update mytable set name='".$_POST['txtmytablename']."' where code='".$_POST['txtmytablecode']."'"; 
    $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); 
};

//erase
if($_POST["mode"]=="erase") {
    $cadena="delete from mytable where code='".$_POST['txtmytablecode']."'"; 
    $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); 
};

// comma delimited file
if($_POST["mode"]=="get")   {
    $rpta="";
    $cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'"; 
    $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); 
    while($row =  mysql_fetch_array($rs)) {
        $rowCount = mysql_num_fields($rs);
        for ($columna = 0; $columna < $rowCount; $columna++)    {
            $rpta.=str_replace($row[$columna],",","").",";
        }
        $rpta.=$row[$columna]."\r\n";
    }
    echo $rpta; 
};

//report
if($_POST["mode"]=="report_a")  {
    $cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'"; 
    $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); 
    while ($row=mysql_fetch_array($rs)) {
        echo $row['code']." ".$row['name']."<br/>"; // colud be a json, html
    };  
};

//json
if($_POST["mode"]=="json_a")    {
    $cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'"; 
    $rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena); 
    $result = array();
    while ($row=mysql_fetch_array($rs)) {
        array_push($result, array("id"=>$row['code'],"value" => $row['name']));
    };  
    echo json_encode($result);
};
?>

【讨论】:

  • 不错的方法,但它不会创建自己的范围。这就是为什么创建一个类更好
【解决方案4】:

您能否提及您使用的是哪个框架? 你的方法是正确的,但我想在这里提两件事。首先从浏览器尝试您的 URL 并检查其是否正常工作。其次不要使用return,在*success: function(data) * data 中只包含输出。所以使用 Echo 而不是 return

【讨论】:

    【解决方案5】:

    对于它的价值,我使用了一个 PHP 代理文件,它接受一个对象作为帖子——我将在此处发布它。它通过提供类名、方法名、参数(作为数组)和返回类型来工作。这也仅限于执行指定的类和要返回的一组有限的内容类型。

            <?php
    
    
        // =======================================================================
            $allowedClasses = array("lnk","objects");    // allowed classes here
        // =======================================================================
    
        $raw =  file_get_contents("php://input");  // get the complete POST
    
        if($raw) {
    
                $data = json_decode($raw);
                if(is_object($data)) {
    
                    $class =   $data->class;        // class:       String - the name of the class (filename must = classname) and file must be in the include path
                    $method =  $data->method;       // method:      String - the name of the function within the class (method)
                    @$params = $data->params;       // params:      Array  - optional - an array of parameter values in the order the function expects them
                    @$type =   $data->returntype;   // returntype:  String - optional - return data type, default: json || values can be: json, text, html
    
            // set type to json if not specified
                    if(!$type) {
                        $type = "json";
                    }
    
            // set params to empty array if not specified
                    if(!$params) {
                        $params = array();
                    }
    
            // check that the specified class is in the allowed classes array
                    if(!in_array($class,$allowedClasses)) {
    
                        die("Class " . $class . " is unavailable.");
                    }
    
                    $classFile = $class . ".php";
    
            // check that the classfile exists
                    if(stream_resolve_include_path($classFile)) {
    
                        include $class . ".php";
    
                    } else {
    
                        die("Class file " . $classFile . " not found.");
                    }           
    
                    $v = new $class;
    
    
            // check that the function exists within the class
                    if(!method_exists($v, $method)) {
    
                        die("Method " . $method . " not found on class " . $class . ".");
                    }
    
            // execute the function with the provided parameters
                    $cl = call_user_func_array(array($v,$method), $params );
    
            // return the results with the content type based on the $type parameter
                    if($type == "json") {
                        header("Content-Type:application/json");
                        echo json_encode($cl);
                        exit();
                    }
    
                    if($type == "html") {
                        header("Content-Type:text/html");
                        echo $cl;
                        exit();
                    }
    
                    if($type == "text") {
                        header("Content-Type:text/plain");
                        echo $cl;
                        exit();
                    }
                }
                else {
                    die("Invalid request.");
                    exit();
                }       
    
        } else {
    
            die("Nothing posted");
            exit();
        }
    
        ?>
    

    要从 jQuery 调用它,你可以这样做:

                var req = {};
                var params = [];
                params.push("param1");
                params.push("param2");
    
                req.class="MyClassName";
                req.method = "MyMethodName";
                req.params = params;
    
                    var request = $.ajax({
                      url: "proxy.php",
                      type: "POST",
                      data: JSON.stringify(req),
                      processData: false,
                      dataType: "json"
                    });
    

    【讨论】:

      【解决方案6】:

      试试这个: 更新的 Ajax:

      $("#submit").on('click', (function(e){
      
          var postURL = "../Controller/Controller.php?action=create";
      
          $.ajax({
              type: "POST",
              url: postURL,
              data: $('form#data-form').serialize(),
              success: function(data){
                  //
              }
          });
          e.preventDefault();
      });
      

      更新控制器:

      <?php
      
      require_once "../Model/Model.php";
      require_once "../View/CRUD.php";
      
      class Controller
      {
      
          function create(){
              $nama = $_POST["nama"];
              $msisdn = $_POST["msisdn"];
              $sms = $_POST["sms"];
              insertData($nama, $msisdn, $sms);
          }
      
      }
      
      if(!empty($_POST) && isset($_GET['action']) && $_GET['action'] == ''create) {
          $object = new Controller();
          $object->create();
      }
      
      ?>
      

      【讨论】:

        【解决方案7】:

        对每个ajax请求添加两个数据,一个是类名,另一个是函数名 如下创建php页面

         <?php
        require_once 'siteController.php';
        if(isset($_POST['class']))
        {
            $function = $_POST['function'];
            $className = $_POST['class'];
            // echo $function;
            $class = new $className();
            $result = $class->$function();
        if(is_array($result))
        {
            print_r($result);
        }
        elseif(is_string($result ) && is_array(json_decode($result , true)))
        {
        print_r(json_decode($string, true));
        }
        else
        {
        echo $result;
        }
        
        }
        ?>
        

        Ajax 请求如下

        $.ajax({
                                url: './controller/phpProcess.php',
                                type: 'POST',
                                data: {class: 'siteController',function:'clientLogin'},
                                success:function(data){
                                    alert(data);
                                }
                            });
        

        类如下

        class siteController
        {     
          function clientLogin()
          {
            return "lion";
          }
        }
        

        【讨论】:

          【解决方案8】:

          我认为通过 AJAX 调用静态 PHP 方法将是一种巧妙的解决方法,该方法也适用于大型应用程序:

          ajax_handler.php

          <?php
          
          // Include the class you want to call a method from
          
          echo (new ReflectionMethod($_POST["className"], $_POST["methodName"]))->invoke(null, $_POST["parameters"] ? $_POST["parameters"] : null);
          

          some.js

          function callPhpMethod(className, methodName, successCallback, parameters = [ ]) {
              $.ajax({
                  type: 'POST',
                  url: 'ajax_handler.php',
                  data: {
                      className: className,
                      methodName: methodName,
                      parameters: parameters
                  },
                  success: successCallback,
                  error: xhr => console.error(xhr.responseText)
              });
          }
          

          你好^^

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-10-24
            • 2016-08-06
            • 1970-01-01
            • 2016-08-05
            • 2011-03-07
            • 1970-01-01
            相关资源
            最近更新 更多