通过Ajax发送数据、类和方法

Sending data, Class, and Method through Ajax

本文关键字:方法 数据 Ajax 通过      更新时间:2023-09-26

如何通过ajax将数据发送到另一个PHP类中的特定方法?在url值中,我指向了类文件,但在哪里可以分配要使用的方法名?

$.ajax({    
        type:'POST',
        url:'ResortController.php',
        data: vidData, 
        cache:false,
        contentType: false,
        processData: false,
        success:function(data){
            console.log("success");
            console.log(vidData);
            //window.location.reload();         
        },
        error: function(data){
            console.log("error");
        }
    });

data:vidData中传递数据,并在调用控制器后指定您的函数名。

url = BASE_PATH + 'ResortController/FUNCTION_NAME';
vidData = {id: 123, vidName: "testVideo"};
$.ajax({    
        type:'POST',
        url:url,
        data: vidData, 
        cache:false,
        contentType: false,
        processData: false,
        success:function(data){
            console.log("success");
            console.log(data);
            //window.location.reload();         
        },
        error: function(data){
            console.log("error");
        }
    });

在函数中使用$_POST,您将在$_POST['vidData']中获得ajax数据。

此外,您还需要调用data而不是vidData变量,以获得ajax console.log(data)的成功。

您需要有一个服务器端机制来处理如何引导请求。假设您发送请求的url只有类声明。。。您需要某种调度器,否则php不知道该做什么:

jQuery:

$.ajax({  
        type:'POST',
        url:'/dispatcher.php',
        data: {
            "data":vidData,
            "class":"ResortController",
            "method":"rMethod"
        },
        cache:false,
        success:function(data){
            console.log("success");
            console.log(vidData);
            //window.location.reload();         
        },
        error: function(data){
            console.log("error");
        }
    });

/dispatcher.php

<?php
// This is dangerous if you have no controls in place to allow/restrict
// a program to run a command
// Anyone could send a cURL request and run an automated class/method through
// this mechanism unless you have some way to restrict that
if(!empty($_POST['class']) && !empty($_POST['method'])) {
    // Here you want to have some way to check that a request is valid and not 
    // made from some outside source to run arbitrary commands
    // I will pretend you have an admin identifier function....
    if(is_admin()) {
        call_user_func_array(array($_POST['class'],$_POST['method']),array('data'=>$_POST['data']));
    }
}