Jquery Ajax and php classes

2019-04-02 01:39发布

I'm trying to learn how to use oop in php. I'm also fairly new to jquery. Is it possible to make an Ajax request to a php class method? I've only ever sent Ajax requests to a file specifically for that purpose and that returns the data I need.

9条回答
地球回转人心会变
2楼-- · 2019-04-02 02:27

Although I would recommend at least understanding how to achieve this manually, you can always use Xajax which allows you to create a php class that is indirectly accessible from your page's javascript.

查看更多
倾城 Initia
3楼-- · 2019-04-02 02:28

Basic answer no, but it can be done easily.

An ajax call itself cannot call class methods. It has not way of initiating the class and then calling the method. It can only cause the PHP file to run on the server via a POST/GET call on X url.

What you can do is use another file to act as a go-between from the ajax to the method. In other words, instead of calling the php file (update.php for example) directly as simple examples show, you can call a go-between file (call it whatever you like, ajax server, ajax router, etc) that uses GET/POST parameters you send to figuere out what method you want to use and what values to pass to it. You could then run the method from that file (initiating the class and calling the method with parameters), and return the results of that method from that file to the ajax calling script.

查看更多
可以哭但决不认输i
4楼-- · 2019-04-02 02:28

*******************JS File test-----**************************
function actionTest(){
	$.ajax({
		type:"POST",
		url:"test2.php",
		data:{"ac":"test","pp":"YHOOOOOOOO"}
	}).done(function(data){
		$("#show").html(data);
	});
}
*******************-----PHP file test2.php-----**************************
<?php
$ac = $_POST['ac'];
$pp = $_POST['pp'];
if($ac =="test"){
	$obj = new Tt();
	$obj->test($pp);
}

class Tt
{
	
	function __construct()
	{
		
	}
	function test($aa){		
		echo "This is test function!".$aa;
	}
}
?>
*******************----HTML file------**************************
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<title>TESTTTTTTT</title>
	<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
    <script src="js/jquery-2.1.4.js" type="text/javascript"></script>
    <script src="js/test.js" type="text/javascript"></script>     
    <link rel="shortcut icon" href="img/icons/icon.png"/>
</head>
<body onload="actionTest()">
<div id="show"></div>
</body>
</html>

查看更多
登录 后发表回答