AJAX 요청 및 PHP 클래스 함수
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->getName()을 호출하여 결과를 반향합니다.그러면 Ajax 스크립트에 대한 응답이 제공됩니다.
동물을 대상으로 하는 대신 이 새로운 스크립트를 Ajax 요청의 대상으로 사용하십시오.php.
OOP 현재 php:
ajax.html program (클라이언트 계층) -> program.php (중간 계층) -> class.php (중간 계층) -> SQL call or SP (db 계층)
현재 DotNet에서 사용 중인 OOP:
ajax.html program(클라이언트 계층) -> program.aspx.vb(중간 계층) -> class.cls(중간 계층) -> SQL call 또는 SP(DB 계층)
실제 솔루션:OOOA, OOP 하지 마세요.
따라서 테이블당 하나의 파일(클래스별로)이 적절한 Ajax 호출을 가지고 있으며 POST 매개 변수(즉, 모드)를 사용하여 각 Ajax 호출을 선택합니다.
내 테이블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을 시도하고 올바르게 작동하는지 확인합니다.둘째, *success: function(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 요청에 대해 두 개의 데이터를 추가합니다. 하나는 클래스 이름이고 다른 하나는 함수 이름 create 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 방법을 호출하는 것은 더 큰 애플리케이션에서도 작동할 수 있는 세련된 해결책이 될 것이라고 생각합니다.
agax_build.dll
<?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({
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){
}
});
//클래스 에이잭스 코드
<?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;
}
}
?>
언급URL : https://stackoverflow.com/questions/17489109/ajax-request-and-php-class-functions
'programing' 카테고리의 다른 글
GZIP과 DEFLATE 압축의 장점은 무엇입니까? (0) | 2023.08.20 |
---|---|
jQuery를 사용한 파이 차트 (0) | 2023.08.20 |
부울 모드에서 사용하는 동안 전체 텍스트 색인을 찾을 수 없습니다. (0) | 2023.08.20 |
부트스트랩 기본 색상을 변경하는 방법은 무엇입니까? (0) | 2023.08.20 |
HTML에서 공백 무시 (0) | 2023.08.20 |