AJAX 请求和 PHP 类函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17489109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:59:18  来源:igfitidea点击:

AJAX request and PHP class functions

phpajax

提问by rajesh

How to call a PHP class function from an ajax call

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

animal.phpfile

animal.php文件

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

Then in my ajax.phpfile I have an ajax request, need to get values from getName function

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

How to do that getName()function can I do like this?

如何执行该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>

回答by Tomas Prado

My answer is the same as Surreal Dreams answer, but with the code.

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

First. Class animal is OK. Leave it like that:

第一的。类动物是OK。让它这样:

animal.php

animal.php

<?php

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

Next. Create a new animalHandler.phpfile.

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

<?php
require_once 'animal.php';

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

Finally. Change your Javascript.

最后。更改您的 Javascript。

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

That's is.

那是。

回答by Surreal Dreams

You need one additional script, because your animal class can't do anything on its own.

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

First, in another script file, include animal.php. Then make an object of the animal class - let's call it myAnimal. Then call myAnimal->getName() and echo the results. That will provide the response to your Ajax script.

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

Use this new script as the target of your Ajax request instead of targeting animal.php.

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

回答by gtryonp

OOP Currently with php:

OOP 目前使用 php:

ajax.html program(client tier) -> program.php (middle tier) -> class.php (middle tier) -> SQL call or SP (db tier)

ajax.html program(client tier) -> program.php (middle tier) -> class.php (middle tier) -> SQL call or SP (db tier)

OOP Currently with DotNet:

目前使用 DotNet 的 OOP:

ajax.html program(client tier) -> program.aspx.vb (middle tier) -> class.cls (middle tier) -> SQL call or SP (db tier)

ajax.html program(client tier) -> program.aspx.vb (middle tier) -> class.cls (middle tier) -> SQL call or SP (db tier)

My real-life solution: Do OOA, do not OOP.

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

So, I have one file per table -as a class- with their proper ajax calls, and select the respective ajax call with a POST parameter (i.e. mode).

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

/* mytable.php */

/* 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);
};
?>

回答by Nabeel Arshad

Can you please mention which are you using any Framework? You method is correct but I want to mention two things over here. First try your URL from the browser and check if its working correctly. Secondly don't use return, in *success: function(data) * data will contain only the output. so use Echorather then return

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

回答by Salvatore Giacinto

For what it is worth, I have used a PHP proxy file that accepts an object as a post -- I will post it here. It works by providing class name, method name, parameters (as an array) and the return type. This is limited as well to only execute classes specified and a limited set of content types to return.

对于它的价值,我使用了一个 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();
    }

    ?>

To call this from jQuery you would then do:

要从 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"
                });

回答by Gaurav

Try this: Updated Ajax:

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

Update Contoller:

更新控制器:

<?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();
}

?>

回答by RinShan Kolayil

For every ajax request add two data, one is class name and other is function name create php page as follows

每个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 request is follows

Ajax请求如下

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

Class is follows

类如下

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

回答by Senfti

I think that woud be a sleek workaround to call a static PHP method via AJAX which will also work in larger applications:

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

ajax_handler.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

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

Greetings ^^

问候^^