使用Jquery&从PHP调用特定函数阿贾克斯 [英] Calling a specific function from PHP with Jquery & Ajax
问题描述
对我来说这是新事物,所以我只是在研究并试图理解它. 如您所见,在php脚本中有2个函数,而我正在尝试用jquery调用特定的函数.
For me this is something new, so I am just researching this and trying to understand it. As you can see in the php script there are 2 functions and I am trying to call a specific one with jquery.
现在,如果我有一个功能,那么我可以做到,但是当我有2个或更多功能时,我就开始陷入困境. 我想当我有2个函数时可以执行此操作,但是一旦有更多变量在起作用或有更多函数,我是否会在php中使用大量if语句?
Now if I have one function then I can do it, but when I have 2 or more I am starting to get stuck. I suppose I could do this when I have 2 functions, but as soon as more variables are in play or more functions do I just make massive if statements in my php?
问题在于,当我将数据库附加到数据库时,我需要考虑所有可能发生的输入. 在使用jQuery&时如何指定特定的php函数?阿贾克斯?
The problem is that when I attach a database to it, I would need to consider all inputs that can happen. How do I specify a specific php function when using jquery & ajax?
//function.php
<?php
function firstFunction($name)
{
echo "Hello - this is the first function";
}
function secondFunction($name)
{
echo "Now I am calling the second function";
}
?>
<?php
$var = $_POST['name'];
if(isset($var))
{
$getData = firstFunction($var);
}
else if(isset($var))
{
$getData = secondFunction($var);
}
else
{
echo "No Result";
}
?>
//index.html
<div id="calling">This text is going to change></div>
<script>
$(document).ready(function() {
$('#calling').load(function() {
$.ajax({
cache: false,
type: "POST",
url: "function.php",
data: 'name=myname'
success: function(msg)
{
$('#calling').html((msg));
}
}); // Ajax Call
}); //event handler
}); //document.ready
</script>
推荐答案
您需要通过数据对象或URL上的GET变量传入参数.要么
You need to pass a parameter in, either via the data object or via a GET variable on the URL. Either:
url: "function.php?action=functionname"
或:
data: {
name: 'myname',
action: 'functionname'
}
然后在PHP中,您可以访问该属性并进行处理:
Then in PHP, you can access that attribute and handle it:
if(isset($_POST['action']) && function_exists($_POST['action'])) {
$action = $_POST['action'];
$var = isset($_POST['name']) ? $_POST['name'] : null;
$getData = $action($var);
// do whatever with the result
}
注意:出于安全原因,一个更好的主意是将可以调用的可用功能列入白名单,例如:
Note: a better idea for security reasons would be to whitelist the available functions that can be called, e.g.:
switch($action) {
case 'functionOne':
case 'functionTwo':
case 'thirdOKFunction':
break;
default:
die('Access denied for this function!');
}
实施示例:
// PHP:
function foo($arg1) {
return $arg1 . '123';
}
// ...
echo $action($var);
// jQuery:
data: {
name: 'bar',
action: 'foo'
},
success: function(res) {
console.log(res); // bar123
}
这篇关于使用Jquery&从PHP调用特定函数阿贾克斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!