AJAX 请求和 PHP 类函数


AJAX request and PHP class functions

如何从 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>

我的回答与超现实之梦的答案相同,但带有代码。

第一。类动物是可以的。就这样吧:

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>

就是这样。

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

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

使用此新脚本作为 Ajax 请求的目标,而不是以 animal.php 为目标。

OOP 目前使用 php:

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

OOP目前与DotNet合作:

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

我的实际解决方案:做

呸呸呸呸呸呸呸呸�

因此,我每个表都有一个文件 - 作为一个类 - 具有正确的 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);
};
?>
你能

提到你正在使用哪些框架吗?你的方法是正确的,但我想在这里提到两件事。首先从浏览器中尝试您的 URL,然后检查它是否正常工作。其次不要使用 return,在 *success: function(data( * data 中将只包含输出。所以使用回声而不是返回

为了它的价值,我使用了一个接受对象作为帖子的 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"
                });

试试这个:更新的 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();
}
?>

对于每个 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";
  }
}

我认为通过

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);

一些.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)
    });
}

问候^^

使用 ajax 调用类函数

非常简单,将类函数名称与 ajax 请求一起发送。

/

/ajax 代码

$.ajax({
url: "ajax.php",
type: "POST",
data: {tid: pId,fun: 'get_hours_by_id'}, //fun key indicate function name
cache: false,
beforeSend: function(){
    $('.btn-disable').prop('disabled', true);
},
error:function(xhr, status, error){                 
    Swal.fire({
        icon: 'error',
        title: 'Error',
        text: error,
    })
    $('.btn-disable').prop('disabled', false);          
},
success: function(response){
}
});

Ajax 代码类

<?PHP
if (isset($_POST['fun'])) 
{
    $Ajax_Object = new ajax();
    $data = strval($_POST['fun']);
    $result = $Ajax_Object->$data(); //call class function and return result.
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($result);
}
class ajax 
{
    public function get_hours_by_id() 
    {
        $reponse = array(
            'data'  => 0,
            'status' => false,
            'message' => "hello"
        );
        return $reponse;  
    }
}
?>