当前位置:   article > 正文

ajax交互php class,AJAX request and PHP class functions

ajax.php class

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.

// =======================================================================

$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:

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"

});

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号