如何从ajax调用php函数?
我熟悉如何使ajax进入php页面并执行一系列操作,然后返回json数据.但是,可以调用驻留在给定页面中的特定函数吗?
I am familiar of how to get ajax to go to a php page an execute a series of things and then return json data. However is it possible to call a specific function which resides in a given page?
基本上我想要的是减少项目中的文件数.因此,我可以将很多常用功能放在一页中,然后只需调用当前所需的任何功能即可.
Basically what I want is to reduce the number of files in a project. So I can put a lot of common functions in one page and then just call whatever the function that I want at the moment.
对于ajax请求
1.在您的网页中包含Jquery库. 例如:
1.Include Jquery Library in your web page. for eg:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
2.单击按钮调用功能
2.Call a function on button click
<button type="button" onclick="create()">Click Me</button>
3.在单击按钮的同时,调用javascript中的create函数.
3.while click on button ,call create function in javascript.
<script>
function create () {
$.ajax({
url:"test.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {registration: "success", name: "xyz", email: "abc@gmail.com"}
success:function(result){
console.log(result.abc);
}
});
}
<script>
在服务器端的test.php文件中,应读取操作POST参数和相应的值,并以php格式执行操作,并以json格式返回,例如
On the server side test.php file, the action POST parameter should be read and the corresponding value and do the action in php and return in json format e.g.
$regstration = $_POST['registration'];
$name= $_POST['name'];
$email= $_POST['email'];
if ($registration == "success"){
// some action goes here under php
echo json_encode(array("abc"=>'successfuly registered'));
}